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 with Mockito.reset()
. After reading the documentation, I'm not sure if this is the way to go.
I believe I have two options:
Mockito.reset()
Question:
Is this a correct, acceptable use of Mockito.reset()
, or should I go with the separate tests?
Mockito provides the capability to a reset a mock so that it can be reused later.
Mockito is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().
Mocking is a way to replace a dependency in a unit under test with a stand-in for that dependency. The stand-in allows the unit under test to be tested without invoking the real dependency.
You might want to try using parameterized tests or the zohhak framework so that you have 1 test run for each combination of boolean values. In that case, there's no need to reset the mocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With