I'm doing unit tests with jUnit 5 and Mockito. In one test, I had to mock a method. Everything works fine. In another test later I'm invoking the same method but this time I don't want Mockito to do anything. Nevertheless, Mockito returns an unasked null
value, which makes my test fail. I thought it was due to the first test, so I added Mockito.reset()
. But it didn't change anything.
Do you understand what's happening behind the scene?
I ran the debug mode to have more info about the object created by Mockito. Among other infos I can read
invocationForStubbing: ecritureComptable.toString();
But I don't know where and when this method is called. Any help appreciated.
EDIT.... Thank you guys. I edited my post to make it clearer and also because I have now a better idea of what possibly happened:
1/ Before each test, I create a mock of the object DaoProxy and I use the mode RETURNS_DEEP_STUBS, which have mockito mock objects nested in DaoProxy
@BeforeAll
private static void injectMockDao() {
DaoProxy daoProxyMock = mock(DaoProxy.class, Mockito.RETURNS_DEEP_STUBS);
AbstractBusinessManager.configure(null, daoProxyMock, null);
}
2/ For a specific test method, I use :
when(getDaoProxy().getComptabiliteDao().getEcritureComptableByRef(Mockito.anyString())).thenReturn(ecritureBDD);
and reset it after use, hopping that by the next call of the all chain, Mockito won't do anything (but it didn't work) :
reset(getDaoProxy().getComptabiliteDao().getEcritureComptableByRef(Mockito.anyString()));
3/ In another test later, i make a call to
getDaoProxy().getComptabiliteDao().getEcritureComptableByRef()
and Mockito - although unasked - returns a null object.
The input of @Gavin makes me assume this is because of the RETURNS_DEEP_STUBS-Mocking of DaoProxy. Mockito mocks the nested object, but since it has no info on what it should return, it returns the default object value : null. This explains why in this case the reset didn't help.
If your object is marked for mocking with @Mock
or you have used the mock
method to create it then Mockito will return the default value for the type, which for objects is null
.
In the failing test you could try to either provide a mocked value in the usual way, or inject a "real" instance of the object being mocked, I believe it is possible to have Mockito to provide a mocked response on a "real" instance of an object.