Maintainable tests with Mockito
Last thursday, I attended a conference where we compared the “Classic” with the “London School” of TDD.
I turns out, many of you are not too familiar with Mocking / believe that mocking will link your test too tight to your implementation code.
Well, the way I see it – Mocking is just a tool. A fool with a tool is still a fool. In other words – it depends. It depends on the way you use mocking. A bad class will have bad tests and vice versa.
Try to do small, tightly encapsulated classes with high cohesion, with no more then 80-100 lines, 1-4 lines per method, if possible, seriously. For the test class, aim to test behavior, not methods, as such, use names starting with “should..” rather then “test…”. This will help you to think in behavior instead of in methods. For the test, try to follow the “arrange act assert” pattern.
The first line(s) should be setting up your test. Only set up what is not given by your Mock by default anyway (null, 0, false). Then one line as “act” – to call your method under test, last but not least, one line to assert the expected behavior, or a verify for void methods, if necessary (try to avoid verifies).
P.S.: I’ve just found this interesting discussion about whether or not to mock: