79442228

Date: 2025-02-15 20:48:37
Score: 1.5
Natty:
Report link

Yes, you're absolutely right, testing AWS SDK v2 is too way verbose.The main issue is that AWS removed interfaces from service clients (like s3.Client), so we can't just mock them directly like we did in v1. That forces us to stub entire clients, which is a pain.

In my opinion, it's better to Wrap AWS clients in a small interface and mock that instead.

Because of using struct instead of interfaces in AWS SDKv2 you cannot mock s3.Client directly.

How to fix? Instead of testing against s3.Client, define a minimal interface for only the methods you need:

type S3API interface {
    PutObject(ctx context.Context, params *s3.PutObjectInput) (*s3.PutObjectOutput, error)
}

type S3Client struct {
    Client *s3.Client
}

func (s *S3Client) PutObject(ctx context.Context, params *s3.PutObjectInput) (*s3.PutObjectOutput, error) {
    return s.Client.PutObject(ctx, params)
}

Now in your real code, you should depend on S3API not s3.Client which makes your mocking simpler.

With the interface in place, we don’t need AWS SDK stubs anymore. We can just do this:

type MockS3 struct{}

func (m MockS3) PutObject(ctx context.Context, params *s3.PutObjectInput) (*s3.PutObjectOutput, error) {
    if *params.Bucket == "fail-bucket" {
        return nil, errors.New("mocked AWS error")
    }
    return &s3.PutObjectOutput{}, nil
}

And you can do this magic everywhere like your entire code, and you might use a robust level of abstraction which not depend on AWS SDK.

See this:

type MyUploader struct {
    s3Client S3API
}

func (u *MyUploader) Upload(ctx context.Context, bucket, key string, body []byte) error {
    _, err := u.s3Client.PutObject(ctx, &s3.PutObjectInput{
        Bucket: &bucket,
        Key:    &key,
        Body:   body,
    })
    return err
}

With this setup, your service doesn’t care whether it’s using a real AWS client or a mock—it just calls PutObject().

Reasons:
  • RegEx Blacklisted phrase (1.5): How to fix?
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Amin Mortezaie