Kotlin:使用 Mockito 模拟 AWS S3 客户端
Kotlin: Mock AWS S3 client using Mockito
我正在尝试模拟使用 AmazonS3ClientBuilder 构建的 S3 客户端。我该怎么做?
这是我的代码:
val s3client: AmazonS3 = AmazonS3ClientBuilder
.standard()
.withRegion(s3BucketRegion)
.build()
val request: PutObjectRequest = PutObjectRequest(
s3BucketName,
"$s3BucketKey/file.json",
ByteArrayInputStream(byteArrayJson),
metadata
).withCannedAcl(CannedAccessControlList.BucketOwnerFullControl)
s3client.putObject(request)
这是我尝试过的方法,但我一直收到 403 错误。这意味着它不是在嘲笑客户端
val mockS3Client = mock(AmazonS3::class.java)
val mockPutObjectRequest = mock(PutObjectRequest::class.java)
val mockPutObjectResult = mock(PutObjectResult::class.java)
//val mockAmazonS3ClientBuilder = mock(AmazonS3ClientBuilder::class.java)
//whenever(mockAmazonS3ClientBuilder.withRegion("").build()).thenReturn(mockS3Client)
whenever(mockS3Client.putObject(mockPutObjectRequest)).thenReturn(mockPutObjectResult)
模拟依赖的一种方法是注入依赖对象。您可以在 Spring 配置 class
中定义一个 AmazonS3
的 bean
@Configuration
class AwsConfig{
@Bean fun amazonS3() = AmazonS3ClientBuilder
.standard()
.withRegion(s3BucketRegion)
.build()
}
而在依赖class中,只需注入对象
@Service
class MyService(
private val s3Client: AmazonS3
){
fun someMethod(){
val request: PutObjectRequest = PutObjectRequest(
s3BucketName,
"$s3BucketKey/file.json",
ByteArrayInputStream(byteArrayJson),
metadata
).withCannedAcl(CannedAccessControlList.BucketOwnerFullControl)
s3client.putObject(request)
}
}
在测试中,您只需将模拟 s3 客户端传递给 MyService
我正在尝试模拟使用 AmazonS3ClientBuilder 构建的 S3 客户端。我该怎么做?
这是我的代码:
val s3client: AmazonS3 = AmazonS3ClientBuilder
.standard()
.withRegion(s3BucketRegion)
.build()
val request: PutObjectRequest = PutObjectRequest(
s3BucketName,
"$s3BucketKey/file.json",
ByteArrayInputStream(byteArrayJson),
metadata
).withCannedAcl(CannedAccessControlList.BucketOwnerFullControl)
s3client.putObject(request)
这是我尝试过的方法,但我一直收到 403 错误。这意味着它不是在嘲笑客户端
val mockS3Client = mock(AmazonS3::class.java)
val mockPutObjectRequest = mock(PutObjectRequest::class.java)
val mockPutObjectResult = mock(PutObjectResult::class.java)
//val mockAmazonS3ClientBuilder = mock(AmazonS3ClientBuilder::class.java)
//whenever(mockAmazonS3ClientBuilder.withRegion("").build()).thenReturn(mockS3Client)
whenever(mockS3Client.putObject(mockPutObjectRequest)).thenReturn(mockPutObjectResult)
模拟依赖的一种方法是注入依赖对象。您可以在 Spring 配置 class
中定义一个AmazonS3
的 bean
@Configuration
class AwsConfig{
@Bean fun amazonS3() = AmazonS3ClientBuilder
.standard()
.withRegion(s3BucketRegion)
.build()
}
而在依赖class中,只需注入对象
@Service
class MyService(
private val s3Client: AmazonS3
){
fun someMethod(){
val request: PutObjectRequest = PutObjectRequest(
s3BucketName,
"$s3BucketKey/file.json",
ByteArrayInputStream(byteArrayJson),
metadata
).withCannedAcl(CannedAccessControlList.BucketOwnerFullControl)
s3client.putObject(request)
}
}
在测试中,您只需将模拟 s3 客户端传递给 MyService