使用模拟测试失败,但应用程序有效



我正在测试一个在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();

但是我得到一个空指针异常

我以这种方式解决了这个问题:

@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);
}

谢谢大家的帮助!

似乎用于存根 mongoCollection 的 find 方法的变量"impegno"在应该表示 Find 类型时具有字符串类型。错误描述非常清楚。

如果我正确理解了这个测试用例,那么它应该看起来像这样:

@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));
}

相关内容

最新更新