[英]How to mock a method with a return value if there is a void method inside this method
I am testing a class that has a testable method (the method itself below) with a return value.我正在测试一个具有可测试方法(下面的方法本身)并带有返回值的类。 Using Mockito I am having a problem.
使用 Mockito 我遇到了问题。 Problem with void method roomDao.updateData(outData);
void 方法 roomDao.updateData(outData) 的问题;
public IEntity getData(SimBasket<DataEntity, SimRequest> request) {
Entity outData = converterData.convertNetToDatabase(request);
roomDao.updateData(outData);
return outData;
}
Here is my test code:这是我的测试代码:
@Test
public void getData() {
simRepo = new SimRepo();
Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}
Error log:错误日志:
org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue: 'updateData' is a void method and it cannot be stubbed with a return value !
org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue: 'updateData' 是一个void 方法,它不能用返回值存根! Voids are usually stubbed with Throwables: doThrow(exception).when(mock).someVoidMethod();
Voids 通常用 Throwables 进行处理: doThrow(exception).when(mock).someVoidMethod();
I don't seem to really understand how to fix this, since the void method is inside a method with a return value.我似乎不太明白如何解决这个问题,因为 void 方法位于具有返回值的方法中。
instead of new SimRepo()
try mock it by using Mockito's mock method:而不是
new SimRepo()
尝试使用 Mockito 的模拟方法模拟它:
@Test
public void getData() {
SimRepo simRepo =Mockito.mock(SimRepo.class);
Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}
Update: If you also want to count the number of times this mock method called use this:更新:如果您还想计算调用此模拟方法的次数,请使用以下命令:
// this will check if mock method getData() with parameter `request` called exactly 1 times or not.
Mockito.verify(simRepo, Mockito.times(1)).getData(request);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.