I' ve got some business logic class:
public class SomeService {
public void doFirst() {}
public void doSecond() {
doFirst();
}
}
and test for it:
public class SomeServiceTest {
private SomeService service;
@Before
public void setUp() {
service = new SomeService();
}
@Test
public void doSecond_someCondition_shouldCallFirst() {
// given
...
// when
service.doSecond();
//then
how to verify doFirst() was called?
}
}
How to verify doFirst() was called not on mock, but real service?
Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: verify(mockObject).someMethodOfMockObject(someArgument);
To check if a method was called on a mocked object you can use the Mockito.verify method: In this example, we assert that the method bla was called on the someMock mock object. You can also check if a method was called with certain parameters:
import static org.mockito.Mockito.*; The exact number of invocations can be asserted via method Mockito#verify (T mock, VerificationMode mode) combined with verification mode Times. You need to provide the target mock object to be verified, the expected number of calls (non-negative), and also the invocation to be verified.
If you would like to check that a method was not called, you can pass an additional VerificationMode parameter to verify: Mockito.verify (someMock, Mockito.times (0)).bla (); This also works if you would like to check that this method was called more than once (in this case we check that the method bla was called 23 times):
I wonder why you want to test, what method your method under tests invoke. Sounds pretty much like whitebox testing to me.
In my opinion, you want to verify the outcome of the invocation and not the way to get there, as this might easily change (i.e. when refactoring).
So if the outcome of doSecond() is the same as doFirst() you could write a test for doFirst() and use the same test (i.e. set of assertions) for testing doSecond().
But if you really want to test, whether doFirst() has been invoked by doSecond() you could wrap your service in a spy and then call the verification on the spy:
//given
SomeService service = new SomeService();
SomeService spy = Mockito.spy(service);
//when
spy.doSecond();
//then
verify(spy).doFirst();
It sounds like you want to avoid the real doFirst being called in your test? if so, try this...
//given
boolean firstCalled = false;
SomeService fakeService = new SomeService {
@Override
public void doFirst() {
firstCalled = true;
}
}
//when
fakeService.doSecond();
// then
assertTrue(firstCalled);
This testing/mocking technique is called 'subclass and override' for obvious reasons.
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