What’s Important to Get Right When Using Mocks

In the best case, you end up with a single-line arrange portion of your test that creates an expectation using Mockito’s when(...).then(...) construct. You have a single-line act, and you have a single assert. These are tests you can quickly read, understand, and trust.

Tests using mocks should clearly state what’s going on. One way we do this is by correlation. In answersAppropriateAddressForValidCoordinates, it’s clear that the expected parameter string of "lat=38.000000&lon=-104.000000" correlates to the act arguments of 38.0 and -104.0. Things obviously aren’t always this easy, but the more you can help the test reader make that connection without having to dig through other code, the better ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.