我想使用 Mockito 来模拟 AmazonS3 并测试从中打开流 然后在我的代码读取流后验证该流是否已关闭。我还想获取从流中读取的字节。像这样的事情:
AmazonS3 client = mock(AmazonS3.class);
when(tm.getAmazonS3Client()).thenReturn(client);
S3Object response = mock(S3Object.class);
when(client.getObject(any(GetObjectRequest.class))).thenReturn(response);
S3ObjectInputStream stream = mock(S3ObjectInputStream.class);
when(response.getObjectContent()).thenReturn(stream);
以某种方式模拟读取方法
MyObject me = new MyObject(client);
byte[] bra me.getBytes(File f, offset, length);
assertEquals(length, bra.length);
verify(stream).close();
最佳答案
您可以使用 Mockito 的 Answer 来模拟流。
String expectedContents = "Some contents";
InputStream testInputStream = new StringInputStream(expectedContents);
S3ObjectInputStream s3ObjectInputStream = mock(S3ObjectInputStream.class);
S3Object s3Object = mock(S3Object.class);
AmazonS3Client amazonS3Client = mock(AmazonS3Client.class);
S3AttachmentsService service = new S3AttachmentsService(amazonS3Client);
when(s3ObjectInputStream.read(any(byte[].class))).thenAnswer(invocation -> {
return testInputStream.read(invocation.getArgument(0));
});
我有一个更广泛的示例 here 。希望有帮助。
关于java - 我想模拟一个扩展InputStream的专有类,模拟读取,验证关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176631/