在循环的情况下不返回 Junit Mock 响应
Junit Mock responses are not returned in case of loop
我对 Junit 测试用例有一些问题,情况如下:
我在 void 方法中有以下方法循环:
List<Message> msgList = service1.getList();
for (Message message : msgList) {
StorageObject object = cloudStorage.readObject(anotherObject);
InputStream inputStream = object .getObjectContent();
String text = IOUtils.toString(inputStream);
// text to object mapping
// third party service call
}
在我的单元测试用例中,我做了以下模拟:
- service1.getList() 到 return 2 个消息对象的列表
mock storageobject 并为其提供一些模拟值,如下所示
StorageObject stObject = new StorageObject();
stObject.setObjectContent(new StorageObjectInputStream(new ByteArrayInputStream( "Hi, This is a dummy and it would be json format".getBytes()), null));
Mockito.when(cloudStorage.readObject(Mockito.any())).thenReturn(stObject);
当我执行测试用例时,第一次迭代它运行良好并且方法执行 returns 是正确的结果但是第二次迭代 inputStream 没有有效值所以文本它 returned为空,为什么这样?任何帮助将不胜感激。
您的 InputStream 在第一次读取后被清空。
您需要为每次迭代重新创建它。
您可以为每个后续调用 configure mockito 到 return 新创建的 InputSteam 模拟对象。
Mockito.when(cloudStorage.readObject(Mockito.any())).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
StorageObject stObject = new StorageObject();
stObject.setObjectContent(new StorageObjectInputStream(new ByteArrayInputStream("Hi, This is a dummy and it would be json format".getBytes()), null));
return stObject;
}
});
我对 Junit 测试用例有一些问题,情况如下: 我在 void 方法中有以下方法循环:
List<Message> msgList = service1.getList();
for (Message message : msgList) {
StorageObject object = cloudStorage.readObject(anotherObject);
InputStream inputStream = object .getObjectContent();
String text = IOUtils.toString(inputStream);
// text to object mapping
// third party service call
}
在我的单元测试用例中,我做了以下模拟:
- service1.getList() 到 return 2 个消息对象的列表
mock storageobject 并为其提供一些模拟值,如下所示
StorageObject stObject = new StorageObject(); stObject.setObjectContent(new StorageObjectInputStream(new ByteArrayInputStream( "Hi, This is a dummy and it would be json format".getBytes()), null)); Mockito.when(cloudStorage.readObject(Mockito.any())).thenReturn(stObject);
当我执行测试用例时,第一次迭代它运行良好并且方法执行 returns 是正确的结果但是第二次迭代 inputStream 没有有效值所以文本它 returned为空,为什么这样?任何帮助将不胜感激。
您的 InputStream 在第一次读取后被清空。
您需要为每次迭代重新创建它。 您可以为每个后续调用 configure mockito 到 return 新创建的 InputSteam 模拟对象。
Mockito.when(cloudStorage.readObject(Mockito.any())).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
StorageObject stObject = new StorageObject();
stObject.setObjectContent(new StorageObjectInputStream(new ByteArrayInputStream("Hi, This is a dummy and it would be json format".getBytes()), null));
return stObject;
}
});