Maintainable tests with Mockito

2 Nov

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:

To mock or not to mock

Mockito

Subscribe now to be informed when my Java Clean Code Video Course launches and to receive a 20% discount. You will also gain access to accompanying course material in the form of printable pdf's and receive another free Java tutorial after you have subscribed. Enter your email address to get these exclusive offers now.

I respect your privacy. I'll NEVER sell, rent or share your email address.
That's more than a policy, it's my personal guarantee!

Leave a Reply

Your email address will not be published. Required fields are marked *