我正在测试一个搜索MongoDB数据库中项目的应用程序。该应用程序可以运行,但是当我运行测试时出现错误。 这是测试类:
@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);
}
我嘲笑了一个MongoCollection对象并监视了受测类:
@Spy
AgendaCollection collection;
@Mock
MongoCollection mongoCollection;
经过测试的方法
public Impegno trovaImpegno(String data){
Impegno imp = new Impegno();
imp = getMongoCollection().findOne("{data:#}", data).as(Impegno.class);
return imp;
}
当我运行应用程序时,在数据库中发现Impegno对象,并且所有对象都能正常工作,但是在测试过程中出现此错误:
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.
我没有尝试过:
doReturn(impegno).when(mongoCollection).find();
但是我得到了NullPointerException
答案 0 :(得分:1)
我这样解决了这个问题:
@Test
public void WhenTrovaImpegnoThenInvokeMongoCollectionFindOne() throws NullPointerException{
String data = "01-11-2018";
FindOne findResult = mock(FindOne.class);
doReturn(mongoCollection).when(collection).getMongoCollection();
doReturn(findResult).when(mongoCollection).findOne("{data:#}", data);
collection.trovaImpegno(data);
verify(mongoCollection).findOne("{data:#}", data);
}
谢谢大家的帮助!
答案 1 :(得分:0)
似乎用于存根mongoCollection的find方法的变量'impegno'在应表示Find类型时具有String类型。错误说明非常清楚。
如果我正确理解了这个测试用例,它应该看起来像这样:
@Test
public void WhenTrovaImpegnoThenInvokeMongoCollectionFindOne(){
String data = "01-11-2018";
Find findResult = mock(Find.class);
doReturn(mongoCollection).when(collection).getMongoCollection();
doReturn(findResult).when(mongoCollection).find(eq("{data:#}"), eq(data));
doReturn(impegno).when(findResult).as(eq(Impegno.class));
collection.trovaImpegno(data);
verify(mongoCollection).findOne(eq("{data:#}"), eq(data));
verify(findResult).as(eq(Impegno.class));
}