我有一个方法,它使用s3.getObject来获取S3Object,并将对象的内容写入临时文件
@Override
public Optional<String> getObject(String s3BucketName, String s3Path) {
try {
S3Object s3Object = s3Client.getObject(new GetObjectRequest(s3BucketName, s3Path));
try (S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent()){
File tmp = File.createTempFile("/tmp/" + UUID.randomUUID().toString(), ".json");
IOUtils.copy(s3ObjectInputStream, new FileOutputStream(tmp));
return Optional.of(tmp.getAbsolutePath());
} catch (Exception e) {
System.err.println(e.getMessage());
}
} catch (AmazonServiceException e) {
String msg = String.format("Service error while getting object=%s in bucket=%s",
s3Path, s3BucketName);
throw new RuntimeException(msg, e);
} catch (SdkClientException e) {
String msg = String.format("Client error while getting object=%s in bucket=%s",
s3Path, s3BucketName);
throw new RuntimeException(msg + e.getMessage());
}
return Optional.empty();
}
我不确定我是否理解如何为这个方法编写单元测试。
@Test
public void getObjectTest() throws UnsupportedEncodingException {
S3Object s3Object = Mockito.mock(S3Object.class);
s3Object.setObjectContent(new StringInputStream(TEST_STRING));
Mockito.when(mockS3Client.getObject(new GetObjectRequest(TEST_S3BUCKET, TEST_S3OBJECT))).thenReturn(s3Object);
s3Accessor.getObject(TEST_S3BUCKET, TEST_S3OBJECT);
verify(mockS3Client).getObject(new GetObjectRequest(TEST_S3BUCKET, TEST_S3OBJECT));
}
我是单元测试的新手,我不确定我可以Assert什么,因为我从方法中只得到了文件的绝对路径。有人能给我一些建议吗?
1条答案
按热度按时间qxsslcnc1#
我建议在测试中更改一些东西。不要模拟
S3Object
,而要从本地文件构建对象,将值设置为模拟对象是不正确的。您也应该加入例外状况的测试。
查看下面的代码