如果此方法中有 void 方法,如何模拟具有 return 值的方法
How to mock a method with a return value if there is a void method inside this method
我正在测试一个 class,它有一个具有 return 值的可测试方法(下面的方法本身)。
使用 Mockito 我遇到了问题。 void 方法问题 roomDao.updateData(outData);
public IEntity getData(SimBasket<DataEntity, SimRequest> request) {
Entity outData = converterData.convertNetToDatabase(request);
roomDao.updateData(outData);
return outData;
}
这是我的测试代码:
@Test
public void getData() {
simRepo = new SimRepo();
Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}
错误日志:
org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue:
'updateData' is a void method and it cannot be stubbed with a return value!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
我似乎不太明白如何解决这个问题,因为 void 方法位于具有 return 值的方法中。
而不是 new SimRepo()
尝试使用 Mockito 的模拟方法模拟它:
@Test
public void getData() {
SimRepo simRepo =Mockito.mock(SimRepo.class);
Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}
更新:
如果您还想计算此模拟方法调用的次数,请使用:
// this will check if mock method getData() with parameter `request` called exactly 1 times or not.
Mockito.verify(simRepo, Mockito.times(1)).getData(request);
我正在测试一个 class,它有一个具有 return 值的可测试方法(下面的方法本身)。 使用 Mockito 我遇到了问题。 void 方法问题 roomDao.updateData(outData);
public IEntity getData(SimBasket<DataEntity, SimRequest> request) {
Entity outData = converterData.convertNetToDatabase(request);
roomDao.updateData(outData);
return outData;
}
这是我的测试代码:
@Test
public void getData() {
simRepo = new SimRepo();
Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}
错误日志:
org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue: 'updateData' is a void method and it cannot be stubbed with a return value! Voids are usually stubbed with Throwables: doThrow(exception).when(mock).someVoidMethod();
我似乎不太明白如何解决这个问题,因为 void 方法位于具有 return 值的方法中。
而不是 new SimRepo()
尝试使用 Mockito 的模拟方法模拟它:
@Test
public void getData() {
SimRepo simRepo =Mockito.mock(SimRepo.class);
Mockito.when(simRepo.getData(request)).thenReturn(new Entity());
}
更新: 如果您还想计算此模拟方法调用的次数,请使用:
// this will check if mock method getData() with parameter `request` called exactly 1 times or not.
Mockito.verify(simRepo, Mockito.times(1)).getData(request);