'How to mock the forEach elements which is iterate over the minioclient collection?
I am using minioClient.listObjects
to fetch all the objects from s3
. It returns the iterable Result<Item>
. Here I was iterating over these results.
public class S3class
{ //this class is part of spring boot application. So here no main class.
public void s3method(){
MinioClient minioClient = MinioClient.builder().endpoint("")
.build();
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder()
.bucket("bucket_name")
.recursive(true)
.startAfter("something")
.build()
);
for (Result<Item> result : results) {
Item item;
try {
System.out.println("inside try");
item = result.get(); ///it returns null. How to mock this
System.out.println("if it reach here, no problem");
}
catch (Exception e) {
System.out.println("problem is here");
throw new Error();
}
Tags tags = minioClient.getObjectTags(
GetObjectTagsArgs.builder()
.bucket(bucket)
.object(item.objectName()) //beforei was tried like result.get().objectName(). but it fails. Here always i want to return "dummy" string. but it gives **null**.
.build()
);
}
}
}
Testing method
@RunWith(MockitoJUnitRunner.class)
public class Testclass{
@InjectMocks
private S3class s3class;
@Mock
private MinioClient minioClient;
@Mock
private Result<Item> result;
@Mock
private Iterable<Result<Item>> results;
@Mock
private Iterator<Result<Item>> iterator;
@Mock
private Consumer<Result<Item>> consumer;
public void testmethod(){
Item item = new Item("dummy") {};
result = new Result<Item>(item);
// Mockito.when(result.get()).thenReturn(item);
Mockito.when(minioClient.listObjects(
Mockito.any(ListObjectsArgs.class)))
.thenReturn(results);
Mockito.doCallRealMethod().when(results).forEach(consumer);
Mockito.when(iterator.hasNext()).thenReturn(true,false);
Mockito.when(iterator.next()).thenReturn(result);
Mockito.when(results.iterator()).thenReturn(iterator);
s3class.s3method();
}
}
I mocked the minioclient
. But I can't mock this result.get().objectName()
. I used when and thenReturn
but no use. Here I want to return some string
whenever result.get().objectName()
called.
I tried this whole day in many ways. But I couldn't. Can anyone help me with this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|