Reputation: 775
So I have test like this:
public class TimesheetServiceTest {
@Mock
Repository repository;
@Mock
ServiceToMockResult serviceToMockResult;
@InjectMocks
private ServiceToTest serviceToTest = new ServiceToTestImpl();
@Test
public void testLongResult() {
when(serviceToMockResult.getResult(any(String.class)))
.thenReturn(20L); //it's supposed to always return 20L
//8 items length result list
List<Long> results = this.serviceToTest.getResults();
//some more testing after ....
}
}
As you can see the serviceToMock.getResult() method gets called inside of the ServiceToTest. So after doing this I get the 8 results I expect but some of them are value 0, and I also noticed that it's always position 5 and 7 in list. It's worth noticing that when I call serviceToMock.getResult() directly in test without passing through the other class, I get the expected result.
Expected Result
20, 20, 20, 20, 20, 20, 20, 20
Actual Result
20, 20, 20, 20, 20, 0, 20, 0
Upvotes: 0
Views: 158
Reputation: 25946
Argument matcher any(String.class)
matches any String, excluding nulls.
See ArgumentMatchers.any documentation:
public static <T> T any(Class<T> type)
Matches any object of given type, excluding nulls.
Most likely you are calling serviceToMockResult.getResult() with a null argument.
As such a call is not stubbed, default value for the return type is returned (which is 0
for long
)
Upvotes: 3
Reputation: 4502
While injecting mocks to a bean/service instead of creating it, let it create by mocks. Also init Mockito anntotation before processing.
Example:
public class TimesheetServiceTest {
@Mock
Repository repository;
@Mock
ServiceToMockResult serviceToMockResult;
// let mockito create the service.
@InjectMocks
private ServiceToTest serviceToTest;
@Test
public void testLongResult() {
// Init mocks
MockitoAnnotations.initMocks(this);
when(serviceToMockResult.getResult(any(String.class)))
.thenReturn(20L);
// This should work fine.
}
}
Upvotes: 0