Mock CloudBlobClient with AutoFac and AutoMock

后端 未结 3 526
误落风尘
误落风尘 2021-01-14 10:07

I\'m trying to write unit tests for my AzureBlobRepository. The repository receives a CloubBlobClient in the constructor. I want to mock the client, but this gives an except

3条回答
  •  星月不相逢
    2021-01-14 10:33

    Those classes should be treated as 3rd party implementation concerns. This means that you have no control over them and we should not mock what we have no control over. They should be encapsulated behind abstractions that you do control and can mock as needed when testing in isolation.

    public interface ICloudBlobClient {
        //...expose only the functionality I need
    }
    
    public class CloudBlobClientWrapper : ICloudBlobClient {
        private readonly CloudBlobClient client;
    
        public CloudBlobClientWrapper(CloudBlobClient client) {
            this.client = client;
        }
    
        //...implement interface wrapping
    }
    

    Classes should depend on abstraction and not concretions for that very reason. Mocking concrete classes tend to have knock on effects

    The wrapper does not need to wrap the client exactly but can aggregate functionality so as not to expose implementation concerns.

    So now when testing in isolation you can mock the abstraction you control

    using (var mock = AutoMock.GetLoose()) {
        var mockClient = mock.Mock();
    
        /// ...and the rest of the test.
    }
    

提交回复
热议问题