Middle+
What good practices and anti-patterns are there in unit testing? How to understand that tests are good?
sobes.tech AI
Answer from AI
Good practices for unit testing:
- Isolation: each test checks only one specific aspect or function.
- Repeatability: tests should give the same result every time they are run, regardless of the environment.
- Performance: unit tests should execute quickly so as not to slow down the development process.
- Clarity: test code should be simple and readable to easily understand what is being tested.
- Use of mocks and stubs: to isolate the tested code from external dependencies.
- Boundary coverage: tests should check not only normal scenarios but also edge cases.
Anti-patterns:
- Testing multiple things at once: complicates understanding and debugging.
- Dependence on external resources: databases, networks, etc., make tests unstable.
- Complex and lengthy tests: hinder maintenance.
- Lack of cleanup after tests: can affect subsequent tests.
- Testing private methods directly: better to test through the public interface.
How to understand if tests are good:
- They run quickly and pass reliably.
- Easy to understand what exactly is being tested.
- When code changes, tests help identify regressions.
- Cover main and boundary cases.
Example of a simple unit test in Go:
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}