gpt4 book ai didi

java - 使用mockito测试失败但应用程序可以工作

转载 作者:行者123 更新时间:2023-11-30 06:02:50 26 4
gpt4 key购买 nike

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

最佳答案

我是这样解决问题的:

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

感谢大家的帮助!

关于java - 使用mockito测试失败但应用程序可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com