如何在Spring中利用Testcontainers测试S3服务抛出AwsServiceException
如何用S3Mock容器模拟AwsServiceException异常场景
你可以利用Adobe S3Mock的特性,通过触发特定操作来模拟真实S3服务抛出的AwsServiceException,以下是几种常见场景的实现方式:
1. 模拟「桶不存在」异常
尝试访问未初始化的桶,会触发NoSuchBucket类型的AwsServiceException:
@Test void testNoSuchBucketException() { // 构建指向S3Mock的客户端 AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration( s3MockContainer.getHttpEndpoint(), s3MockContainer.getRegion() )) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("test", "test"))) .withPathStyleAccessEnabled(true) .build(); // 验证异常抛出并校验错误码 AwsServiceException exception = assertThrows(AwsServiceException.class, () -> { s3Client.listObjectsV2("non-existent-bucket"); }); assertEquals("NoSuchBucket", exception.getErrorCode()); }
2. 模拟「对象不存在」异常
尝试获取桶内不存在的对象,会触发NoSuchKey类型的AwsServiceException:
@Test void testNoSuchKeyException() { AmazonS3 s3Client = buildS3Client(); AwsServiceException exception = assertThrows(AwsServiceException.class, () -> { s3Client.getObject(BUCKET_NAME, "non-existent-object.txt"); }); assertEquals("NoSuchKey", exception.getErrorCode()); } // 封装客户端构建逻辑复用 private AmazonS3 buildS3Client() { return AmazonS3ClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration( s3MockContainer.getHttpEndpoint(), s3MockContainer.getRegion() )) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("test", "test"))) .withPathStyleAccessEnabled(true) .build(); }
3. 模拟「桶非空无法删除」异常
S3默认不允许删除非空桶,尝试此操作会触发BucketNotEmpty类型的AwsServiceException:
@Test void testBucketNotEmptyException() { AmazonS3 s3Client = buildS3Client(); // 先向测试桶上传一个对象 s3Client.putObject(BUCKET_NAME, "test-object.txt", "test content"); // 验证删除非空桶时抛出异常 AwsServiceException exception = assertThrows(AwsServiceException.class, () -> { s3Client.deleteBucket(BUCKET_NAME); }); assertEquals("BucketNotEmpty", exception.getErrorCode()); }
4. 模拟「对象过大」异常
通过配置S3Mock的最大对象大小限制,上传超出限制的内容会触发EntityTooLarge类型的AwsServiceException:
首先修改容器初始化配置:
@Container public static final S3MockContainer s3MockContainer = new S3MockContainer(DockerImageName.parse("adobe/s3mock:2.4.13")) .withInitialBuckets(BUCKET_NAME) .withCommand("--max-object-size", "100"); // 设置最大对象大小为100字节
然后编写测试用例:
@Test void testEntityTooLargeException() { AmazonS3 s3Client = buildS3Client(); // 创建超过100字节的内容 String largeContent = "a".repeat(101); AwsServiceException exception = assertThrows(AwsServiceException.class, () -> { s3Client.putObject(BUCKET_NAME, "large-object.txt", largeContent); }); assertEquals("EntityTooLarge", exception.getErrorCode()); }
除了上述场景,S3Mock还支持模拟AccessDenied(权限不足)、InvalidBucketName(非法桶名)等绝大多数S3原生错误码,只需触发对应的违规操作即可。
内容的提问来源于stack exchange,提问作者user1555190
相关产品推荐
相关产品推荐

