I'm testing an application that searches items in a MongoDB database. The application works but when I run the test, there is an error. This is the test class:
@Test
public void WhenTrovaImpegnoThenInvokeMongoCollectionFindOne(){
String data = "01-11-2018";
doReturn(mongoCollection).when(collection).getMongoCollection();
doReturn(impegno).when(mongoCollection).find("{data:#}", data).as(Impegno.class);
collection.trovaImpegno(data);
verify(mongoCollection, times(1)).findOne("{data:#}", data).as(Impegno.class);
}
I mocked a MongoCollection object and spied the class under test:
@Spy
AgendaCollection collection;
@Mock
MongoCollection mongoCollection;
The tested method:
public Impegno trovaImpegno(String data){
Impegno imp = new Impegno();
imp = getMongoCollection().findOne("{data:#}", data).as(Impegno.class);
return imp;
}
When I run the application, Impegno objects are found in the database and all works but during the test I get this error:
WhenTrovaImpegnoThenInvokeMongoCollectionFindOne(agenda.AgendaCollectionTest) Time elapsed: 0.013 sec <<< ERROR!
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
String cannot be returned by find()
find() should return Find
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
I evne tried without:
doReturn(impegno).when(mongoCollection).find();
But I get a NullPointerException