said to Alice, "Have you seen the Mock Turtle yet?" "No," said Alice. "I don't even know what a Mock Turtle is." "It's the thing Mock Turtle Soup is made from," said the Queen. —Alice in Wonderland, chapter 9 2
soIware system do not work in isola<on, but collaborate with other parts to get their job done. In a lot of cases, we do not care about using real collaborators implementa<on in unit tes<ng, as we trust these collaborators. Henri Tremblay, easymock author
simple : as soon as you got a dependency. Nevertheless, as you will see, when mocking becomes too complex, it often means that your class should be split and redesigned. Mocking makes testing more complicated. Try to stick to a common/comprehensible structure inside your project’s tests, this will make them much easier to read. Further on, we will see : ‘’GIVEN WHEN TEST‘’ which is a good structure, but not the only one.
add logic for a test. You would need to test it… • Use test coverage tools to see how much your code is tested. • Structure your tests • Name your tests well (At Groupon we now use testSomething_should_returnSomethingOrDoSomething_when_thisConditionOrThisConditionApplies) • Always use the same assertion set, do not mix. We use Hamcrest and core matchers. • Do not make tests slow. (>100ms). It kills the team productivity. • Do never use system date, make all tests 100% reproducible
co -b temp b1fef A Mock Object is a test-oriented replacement for a collaborator. It is conﬁgured to simulate the object that it replaces in a simple way. Henri Tremblay, still… Mocks are Stubs made easy. …With some subtile differences.
dependencies. Otherwise you run real code, which is bad : • it appears as covered by tests while it is not. You bullshit yourself. • it slows down tests • it is not a unit test • Learn advanced mocking techniques : • Partial mocking & using ﬁnal • Captures • If you can’t mock it as you want, it’s wrong.
mock when possible, more than all when the real implementation is costly (DB, network) 2. design classes to be mocked easily (avoid ﬁnal & static methods) 3. Use DI to inject mocks 4. verify state changing methods Don’ts: 1. overuse mocks. When there are too many things to mock, there is probably a better design. 2. don’t forget to reset mocks 3. don’t forget to replay mocks