我有一段將 json 上傳到 s3 的代碼
private final S3Client s3Client;
private final String bucketName;
public S3ClientWrapper(final Config s3Config) {
final String region = s3Config.getString(REGION_CONFIG_NAME);
bucketName = s3Config.getString(BUCKET_NAME);
final S3ClientBuilder s3ClientBuilder = S3Client.builder();
s3ClientBuilder.region(Region.of(region));
s3Client = s3ClientBuilder.build();
}
public boolean sendEvents(List<Obj> events) {
String key = getKey();
PutObjectRequest objectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
.build();
try {
s3Client.putObject(objectRequest, RequestBody.fromContentProvider(() -> {
PipedOutputStream outputStream = new PipedOutputStream();
GZIPOutputStream gzipOutputStream = null;
try {
gzipOutputStream = new GZIPOutputStream(outputStream);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
GZIPOutputStream finalGzipOutputStream = gzipOutputStream;
events.stream().map(Json::writeValueAsString)
.map(json -> json "\n")
.forEach(json -> {
try {
finalGzipOutputStream.write(json.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
try {
return new PipedInputStream(outputStream);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}, "application/octet-stream"));
return true;
}catch (S3Exception e) {
log.error("failed to send raw data events to S3", e);
return false;
}
}
我想對無法上傳到 S3 并引發 S3Exception 的用例進行單元測驗。如何撰寫單元測驗來測驗我的函式中的這種場景?
uj5u.com熱心網友回復:
我在這里使用 Mockito,但在其他庫的情況下機制會相似。我們需要創建模擬s3Client并將其注入測驗類。在呼叫測驗方法之前,我們必須宣告模擬的預期行為,在這種情況下是 throwing S3Exception。
由于使用了靜態S3Client.builder()方法,我們需要使用該mockStatic方法來模擬客戶端創建,我們需mockito-inline要這樣做(我將鏈接下面的檔案參考)。
@Test
void s3ExceptionThrown() {
try (var mocked = Mockito.mockStatic(S3Client.class)) {
// creation of the two mock objects below can be moved before the try
var builder = mock(S3ClientBuilder.class);
var s3Client = mock(S3Client.class);
// to mock a static method we have to use `when` method from the object created by `mockStatic`
mocked.when(S3Client::builder).thenReturn(builder);
// here we mock non-static methods, so standard `Mockito.mock` method can be used
when(builder.build()).thenReturn(s3Client);
when(s3Client.putObject(any(), any(), any()).thenThrow(new S3Exception());
var testedWrapper = new S3ClientWrapper(/* config */);
var result = testedWrapper.sendEvents(null); // param irrelevant for this test
assertFalse(result);
}
}
(重要提示:代碼是在手機記事本中撰寫的,因此可能編譯不好,但顯示了機制,作為一個概念應該可以正常作業)
- 模擬靜態
- 模擬行內
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/511510.html
標籤:爪哇亚马逊-s3朱尼特
