Reputation: 29260
According to the documentation, non stubbed methods return null. I want to test a method that should return "null" under some circumstances, however the test fails with the exception indicating the method was not called.
This is the test init function:
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
mDataEntry = getFakeEntry();
when(mRepository.getEntry(1L)).thenReturn(mDataEntry);
mGetEntry = new GetEntryImpl(mRepository);
}
and this is the failed test:
@SuppressWarnings("unchecked")
@Test
public void testGetEntry_failure() throws Exception {
mGetEntry.execute(2L, mCallback);
verify(mRepository).getEntry(eq(2L));
verify(mCallback).onError(anyString(), Mockito.any(Exception.class));
}
the execute method calls the mocked object mRepository function getEntry(2L) which I was expecting to return null. However, this is what Mockito tells me when I run the test:
Wanted but not invoked:
mRepository.getEntry(2);
-> at com.xyz.interactor.GetEntryTest.testGetEntry_failure(GetEntryTest.java:54)
Actually, there were zero interactions with this mock.
I tried adding
when(mRepository.getEntry(2L)).thenReturn(null);
to the init function, but it makes no difference. If I return a valid object instead of null, then the test fails as expected, because the onError function is not called (so the mocked object's function for value 2L is being called when I specify a valid return value).
How can I have the mocked object return null for a set of values?
Edit:
here's the code for the function under test:
@Override
public void execute(final long id, final Callback<DataEntry> callback) {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
DataEntry dataEntry = mDataEntryRepository.getEntry(id);
if (dataEntry != null) {
callback.onResult(dataEntry);
} else {
callback.onError("TODO", null);
}
}
});
}
and for reference, the success test works:
@SuppressWarnings("unchecked")
@Test
public void testGetEntry_success() throws Exception {
mGetEntry.execute(1L, mCallback);
verify(mRepository).getEntry(eq(1L));
verify(mCallback).onResult(eq(mDataEntry));
}
Upvotes: 1
Views: 8791
Reputation: 133
I don't think the problem is with Mockito default values / returning null.
I wrote a modified SSCCE, and the tests run fine for me. I don't have the android API, so I couldn't use the AsynchTask.execute(). From what I understand, this code would run in a separate thread, so you might not be guaranteed that the code was run before verify is called. If you take out the AsynchTask and implement execute as follows, does it still fail? Is it possible for an exception to be thrown in execute?
public void execute( final long id, final Callback<DataEntry> callback) {
DataEntry dataEntry = mDataEntryRepository.getEntry(id);
if (dataEntry != null) {
callback.onResult(dataEntry);
} else {
callback.onError("TODO", null);
}
}
Upvotes: 1