Mock | Testing
Spy#
Spies are a kind of mock which can record how a dependency is used. They can record the arguments sent in, how many times it has been called, etc.
main.go
main_test.go
- If your mocking code is becoming complicated or you are having to mock out lots of things to test something, you should listen to that bad feeling and think about your code. Usually it is a sign of
- The thing you are testing is having to do too many things (because it has too many dependencies to mock)
- Break the module apart so it does less
- Its dependencies are too fine-grained
- Think about how you can consolidate some of these dependencies into one meaningful module
- Your test is too concerned with implementation details
- Favour testing expected behaviour rather than the implementation
what level to test exactly?#
- The definition of refactoring is that the code changes but the behaviour stays the same. If you have decided to do some refactoring in theory you should be able to make the commit without any test changes. So when writing a test ask yourself
- Am I testing the behaviour I want, or the implementation details?
- If I were to refactor this code, would I have to make lots of changes to the tests?
- Although Go lets you test private functions, I would avoid it as private functions are implementation detail to support public behaviour. Test the public behaviour. Sandi Metz describes private functions as being "less stable" and you don't want to couple your tests to them.
- I feel like if a test is working with more than 3 mocks then it is a red flag - time for a rethink on the design
- Use spies with caution. Spies let you see the insides of the algorithm you are writing which can be very useful but that means a tighter coupling between your test code and the implementation. Be sure you actually care about these details if you're going to spy on them
Test Doubles#
The "proper" term for mocks are "test doubles"
Under test doubles, there are various types like stubs, spies and indeed mocks! Check out Martin Fowler's post for more detail.