Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Amazon S3 Client for a .NET unit test

I note that the important members of AmazonS3Client are virtual, so a Mock<AmazonS3Client> should be easy. But

new Mock<AmazonS3Client>()

using Moq, got me an error saying that there was no valid RegionEndpoint.

So obviously a little more is required.

like image 792
Chris F Carroll Avatar asked Mar 28 '18 22:03

Chris F Carroll


1 Answers

Instead of tightly coupling the code to implementation concerns, take note that AmazonS3Client class implements IAmazonS3 (v2,v3) or AmazonS3 (v1) interface according to referenced AWS SDK for .NET Documentation.

public class AmazonS3Client : IAmazonS3, IDisposable {
    //...
}

I would suggest you have your code depend on the abstraction (interface) and not on the implementation (class).

public class MyClass {
    private readonly IAmazonS3 client;

    public MyClass(IAmazonS3 client) {
        this.client = client;
    }

    //...
}

That would then allow greater flexibility when swapping dependencies with mocks when testing in isolation.

You have already experienced that added dependencies needed to mock the implementation of AmazonS3Client which can be avoided if the interface is used as the dependency.

s3ClientMock = new Mock<IAmazonS3>();

The Setup of the mocked interface can be done as you would normally as already demonstrated in your answer.

In production the properly configured implementation can be injected into dependent classes.

like image 156
Nkosi Avatar answered Oct 23 '22 20:10

Nkosi