Junior — Middle
Can you describe the main principles and standards for writing tests?
sobes.tech AI
Answer from AI
Main principles and standards for writing tests in C#:
- Clarity and simplicity: tests should be understandable and easy to read.
- Isolation: each test should verify only one aspect of functionality and not depend on other tests.
- Repeatability: tests should produce the same result every time they are run.
- Automation: tests should run automatically without manual intervention.
- Use of the Arrange-Act-Assert (AAA) pattern:
- Arrange — prepare data and environment.
- Act — perform the action.
- Assert — verify the result.
Example of a simple test using NUnit:
[Test]
public void Add_TwoNumbers_ReturnsSum()
{
// Arrange
var calculator = new Calculator();
// Act
var result = calculator.Add(2, 3);
// Assert
Assert.AreEqual(5, result);
}
- Naming tests: usually reflects the condition and expected result, for example
MethodName_StateUnderTest_ExpectedBehavior. - Minimize external dependencies: use mocks and stubs to isolate the tested code.
Adhering to these principles helps create reliable and maintainable tests.