We need to talk about testing
I&#x27;m irrationally passionate about testing. Shameless plug: (rendered version at <a href="https:&#x2F;&#x2F;gist.github.com&#x2F;androidfred&#x2F;501d276c7dc26a5db09e893bb7c9f3ee" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;androidfred&#x2F;501d276c7dc26a5db09e893b...</a>)<p># Test your tests<p>## Summary: test interfaces, not implementations<p>Tests that pass when something is actually broken, and fail when things actually do work, are worse than useless- they are positively harmful.<p>## The requirement<p>Let&#x27;s say we&#x27;ve been tasked with returning `400` when `GET` `&#x2F;users&#x2F;&lt;userId&gt;` is called with a negative `userId`.<p>## The test<p>The requirement can be turned into a test that hits the endpoint with a negative `userId` and checks that a `400` is returned:<p>```java
    @Test
    public void getUser_InvalidUserId_400() {
        expect().statusCode(400).when().get(&quot;&#x2F;users&#x2F;-1&quot;);
    }
```<p>## Implementation<p>A ubiquitous style of implementation may look something like this: (ignore whether you like the style of implementation or not, it&#x27;s just an example)<p>```java
public class UserResource {<p><pre><code>    @Inject
    private UserService userService;
    
    @GET
    @Path(&quot;&#x2F;users&#x2F;{userId}&quot;)
    public Response getUser(@PathParam(&quot;userId&quot;) final Long userId) {
        try {
            return Response.ok(userService.findById(userId)).build();
        } catch (final UserException e) {
            return Response.status(e.getErrorCode()).build();
        }
    }</code></pre>
}
```<p>```java
public UserService {<p><pre><code>    @Inject
    private UserDao userDao;

    public User findById(final Long userId) throws UserException {
        if ((userId == null) || (userId &lt;= 0)) {
            throw new UserException(&quot;Invalid arguments&quot;, 400);
        }
        return userDao.findById(userId);
    }</code></pre>
}<p>```<p>## Another test<p>Everyone knows a test hitting the endpoint is not enough- more tests are required. A ubiquitous style of additional test may look something like this:<p>```java
public class UserResourceTest {<p><pre><code>    @InjectMocks
    private UserResource userResource = new UserResource();

    @Mock
    private UserService userService;

    @Test
    public void getUser_InvalidParams_400() throws UserException {
        doThrow(new UserException(INVALID_ARGUMENTS, 400)).when(userService).findById(-1L);
        assertThat(userResource.getUser(-1L).getStatus(), is(equalTo(400)));
    }</code></pre>
}
```<p>## Test the tests<p>### Break something<p>Let&#x27;s say the negative `userId` check is removed from the `UserService`. (by mistake or whatever)<p>The test that hits the endpoint will fail, because it will no longer get a `400` when `GET` `&#x2F;users&#x2F;&lt;userId&gt;` is called with a negative `userId`. This is exactly what we want out of a test!<p>The additional test however will pretend the negative `userId` check is still in the service and pass. *This is literally the exact opposite of what we want out of a test!*<p>### Refactor something<p>Or, instead, let&#x27;s say the `UserResource` is refactored to use a `NewBetterUserService`. (the `NewBetterUserService` still throws an exception on negative `userId`)<p>The test that hits the endpoint will pass, because it will still get a `400` when `GET` `&#x2F;users&#x2F;&lt;userId&gt;` is called with a negative `userId`. This is exactly what we want out of a test!<p>The additional test however will fail because it expects the `UserResource` to call the (old) `UserService`. *This is literally the exact opposite of what we want out of a test!*<p>### But... The `UserServiceTest` would fail<p>Maybe there&#x27;s a `UserServiceTest` that would fail if the negative `userId` check is removed from the `UserService`:<p>```java
public class UserServiceTest {<p><pre><code>    @Test
    public void findById_InvalidParams_400() throws UserException {
        expectedException.expect(UserException.class);
        expectedException.expectMessage(&quot;Invalid arguments&quot;);
        assertThat(expectedException.errorCode(), is(equalTo(400)));
        
        userService.findById(-1L);
    }</code></pre>
}
```<p>It&#x27;s irrelevant. The `UserResourceTest` test is still a bad test, because it fails on refactoring. And even if there is a `UserServiceTest` that fails if the negative `userId` check is removed from the `UserService`, the `UserResourceTest` doesn&#x27;t fail if there is no such `UserServiceTest`, or if there is but it&#x27;s incorrectly implemented etc. It just pretends the negative `userId` check is in the `UserService` and passes.<p>If you were absolutely adamant about testing the implementation (which you shouldn&#x27;t be, because implementation tests fail on refactoring, making them bad tests), the &quot;correct&quot; way of testing that would be:<p>```java
public class UserResourceTest {<p><pre><code>    private UserResource userResource = new UserResource(new UserService()); &#x2F;&#x2F;not a mock

    @Test
    public void getUser_InvalidParams_400() throws UserException {
        assertThat(userResource.getUser(-1L).getStatus(), is(equalTo(400)));
    }</code></pre>
}
```<p>Because now, if the negative `userId` check is removed from the `UserService` the test will fail. But since it also fails on refactoring, it&#x27;s still a bad test.<p>### But... Mocks are useful<p>Yes, mocks are useful, and they do have a place. Eg, instead of connecting to a real db, the DAO methods could be mocked, and REST calls to other services etc could be mocked too. They&#x27;re external dependencies not part of the core of the system under test. The case made here isn&#x27;t that mocks are never useful or always bad, it&#x27;s that mock testing is often used excessively for <i>internals</i> of the system under test, which doesn&#x27;t make sense.<p>Also, I&#x27;d still argue that, by default, there should still be a strong preference for, rather than mocking DAO calls to db and REST calls to other services, actually spinning up a real in memory db (eg [<a href="https:&#x2F;&#x2F;github.com&#x2F;vorburger&#x2F;MariaDB4j](https:&#x2F;&#x2F;github.com&#x2F;vorburger&#x2F;MariaDB4j)" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;vorburger&#x2F;MariaDB4j](https:&#x2F;&#x2F;github.com&#x2F;v...</a> lets you do this), and actually WireMocking calls to other services. Then, more of the system under test is being tested, with less effort.<p>Ie unlike with regular mock testing, it&#x27;s verified that the app doesn&#x27;t just call a DAO method but also that DAO method actually connects to the db, runs the expected query and returns the expected result based on the primed content in the db, and that the app actually hits the configured external service url with the expected request and handles the primed response based on the Wiremock stub etc etc.<p>While such tests take a bit longer to run, you write <i>far</i> fewer, higher quality, less brittle tests, because you&#x27;re not having to write and maintain `n<i>n` mock tests between every layer of your app internals to check every single call on the way through the stack. You can freely refactor literally </i>all* the internals all you want without having to change the tests at all - they will keep passing as long as everything works and they will fail if something doesn&#x27;t. (which, again, is exactly what you want)<p>## Terminology<p>The test that hits the endpoint is commonly referred to as a &quot;integration test&quot;, and the other test is commonly referred to as a &quot;unit test&quot;.<p>Kent Beck (the originator of test-driven development) defines a unit test as &quot;a test that runs in isolation from other tests&quot;. This is very different from the definition of a unit test as &quot;a test that tests a class&#x2F;method in isolation from other classes&#x2F;methods&quot;. *The test that hits the endpoint satisfies the original definition.*<p>But it doesn&#x27;t really matter if you want to call a given test an &quot;integration&quot; test or a &quot;unit&quot; test. The point is the test fails when something breaks and passes when something is improved. If it does the opposite, it&#x27;s not a good test.<p>## More on the topic<p>* <a href="http:&#x2F;&#x2F;googletesting.blogspot.com.au&#x2F;2013&#x2F;08&#x2F;testing-on-toilet-test-behavior-not.html" rel="nofollow">http:&#x2F;&#x2F;googletesting.blogspot.com.au&#x2F;2013&#x2F;08&#x2F;testing-on-toil...</a><p>* <a href="http:&#x2F;&#x2F;codebetter.com&#x2F;iancooper&#x2F;2011&#x2F;10&#x2F;06&#x2F;avoid-testing-implementation-details-test-behaviours&#x2F;" rel="nofollow">http:&#x2F;&#x2F;codebetter.com&#x2F;iancooper&#x2F;2011&#x2F;10&#x2F;06&#x2F;avoid-testing-imp...</a><p>## Misc<p>There are other problems with the example, such as eg<p>* Primitive Obsession: using a Long to represent `userId` and using procedural inline checks in the service to check for negative `userId`. Instead, create a class `UserId` that encapsulates and enforces its own checks.<p>* Hidden Dependencies: `UserResource` has a hidden dependency on `UserService` and `UserService` has a hidden dependency on `UserDao`. Dependency Injection frameworks like Spring encourage such hidden dependencies, and the excessive use of mocks in unit tests.<p>* The service shouldn&#x27;t know about HTTP error codes.<p>These are simplifications in order to keep the example short - the scope of this article is testing.