How to Make Unit Tests more Likeable
Posted on Mon 04 April 2016 in General Software Development, Testing
What are these unit tests good for? Are we testing Mockito?
This is what a colleague asked another colleague a couple of days ago. He was referring to some rather complicated and long unit tests that used a lot of mocks and verify statements. I knew what he was talking about since I had seen quite a few tests like that myself.
Whenever a JUnit test method has more than ten lines or so, I get suspicious (and sometimes start crying). Add a few ArgumentCaptors and I'm done with that test. If I'm supposed to fix a test like that, I tend to give up quickly and rather delete the test method than try to understand what is being tested and why it fails.
A good test, however, makes me smile. It's short, concise and readable
because it follows the arrange, act, assert principle. It uses
Mockito's fluent API if it uses Mockito at all. That's anyString()
instead of Mockito.anyString()
and times(2)
instead of VerificationModeFactory.times(2)
(which is Mockito's internal API btw). And mocks, stubs, spies, and
dummy objects are set up in the @Before
method instead of every test method. This saves a lot of boilerplate code and makes me want to fix the test if it breaks.