mardi 22 décembre 2015

Appropriate use of Mockito.reset()?

From Mockito.reset() documentation:

Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. Normally, you don't need to reset your mocks, just create new mocks for each test method. Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests.

I have servicemethod which is called from the frontend, with a DTO containing 3 Booleans as the only argument - let's call them a, b and c:

public void executeService(AbcDTO dto) { (...) }

Depending on the values of the Booleans, the service then calls aManager.a(), bManager.b() and cManager.c(). Indeed, I could do this in 3 separate servicemethods, but I'd rather not.

I wanted to unittest every possible combination of the booleanvalues a, b and c, so I wrote something like:

@Test
public void testABC() {
    // Mock aManager, bManager, cManager
    for(boolean a : asSet(true, false)) {
        for(boolean b : asSet(true, false)) {
            for(boolean c : asSet(true, false)) {
                AbcDTO dto = new AbcDTO(a, b, c);

                service.executeService(dto);

                verify(aManager, times(a ? 1 : 0)).a();
                verify(bManager, times(b ? 1 : 0)).b();
                verify(cManager, times(c ? 1 : 0)).c();
                reset(aManager, bManager, cManager);
            }
        }
    }
}

I think this is a test which clearly indicates the purpose of executeService for future readers, but it only runs green because with Mockito.reset(). After reading the documentation, I'm not sure if this is the way to go.

I believe I have two options:

  • Use Mockito.reset()
  • Write separate unittests for each combination (so 8 tests with lots of copy-pasting)

Question:
Is this a correct, acceptable use of Mockito.reset(), or should I go with the separate tests?

Aucun commentaire:

Enregistrer un commentaire