Kar*_*l K 1 java unit-testing inputstream mockito
我想使用 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);
somehow mock the read method
MyObject me = new MyObject(client);
byte[] bra me.getBytes(File f, offset, length);
assertEquals(length, bra.length);
verify(stream).close();
Run Code Online (Sandbox Code Playgroud)
您可以使用 Mockito 的答案来模拟流。
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));
});
Run Code Online (Sandbox Code Playgroud)
我这里有一个更广泛的例子。希望有帮助。
| 归档时间: |
|
| 查看次数: |
5158 次 |
| 最近记录: |