I have some problem with Junit testcases , below is the case : I have below method loop inside the void method :
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
}
in my unit testcase, i have done below mocking :
mock storageobject and provided it some mock values as below
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 );
When i execute the testcase, for first iteration it works perfectly and method execution returns the correct result but for second iteration inputStream doesn't have the valid values so text it returned as null, why so? Any help would be appreciated.
Your InputStream is being emptied after the first read.
You need to recreate it for each iteration. You can configure mockito to return a newly created InputSteam mock object for each consequent call.
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;
}
});