Home > Blockchain >  Kotlin: Mock AWS S3 client using Mockito
Kotlin: Mock AWS S3 client using Mockito

Time:06-03

I'm trying to mock the S3 client which is built using AmazonS3ClientBuilder. How do I do it?

Here is my code:

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)

Here is what I tried, but I keep getting 403 error. This means it is not mocking the client

        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)

CodePudding user response:

One of the approaches to mock dependencies is by injecting dependent object. You can define a bean of AmazonS3 in a Spring configuration class

@Configuration
class AwsConfig{
  @Bean fun amazonS3() = AmazonS3ClientBuilder
                .standard()
                .withRegion(s3BucketRegion)
                .build()

}

And in the dependent class, just inject the object

@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)
  }
}

In the test, you would just pass a mock s3 client to MyService

  • Related