Test Doubles Intro
I think it’s important to learn the basic concepts and how to create test doubles by hand before launching into the details of a specific mocking framework.
- 15 min connect: three facts about mocks
- 10 min concept: Test Doubles
- 35 min concrete: Tire Pressure
- 5 min conclusions: When to use a stub?
Connect - Test Doubles
Give me Three Facts about Mocks. Raise your hand if you have a fact to tell me.
Concept - Test Doubles
Go through Meszaros’ definitions of Test Double, Mock, Stub, Fake. Focus on the Stub to begin with - this is the simplest kind of test double.
Explain that a stub is useful when the real object would
- make your test slow
- be difficult to construct
- make your test unreliable
- be difficult to get into a particular (error) state
Note that we don’t want the object being tested to know that it got a test double instead of a real collaborator, so we need an abstraction or interface that both objects implement. We also need some kind of Dependency Injection so we can substitute the collaborator.
Tire Pressure. First ask them to review the code and work out which collaborator we want to replace with a test double. When everyone has spent 5-10 minutes reading the code, go through how you should introduce the abstraction/interface for Sensor and how to inject this dependency. Then ask them to write the unit tests for the Alarm class including the ‘check’ method.
If they finish this task quickly, ask them to work on Turn Ticket.
In what situations should you use a stub? Note down some answers and share them with the group.