Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock the DocumentClientException that the Azure DocumentDB client library throws?

I'm trying to write some unit tests around code that queries Azure Document DB. In particular, I'm trying to ensure that error handling works correctly. The only difficulty is that I can't mock the DocumentClientException class that the client library throws when it receives an error from DocumentDB. DocumentClientException implements ISerializable, so when I try to mock it (with Moq), I get an exception saying that the mock object failed to provide a deserialization constructor.

Has anyone successfully mocked the Azure DocumentDB document client exception? If so, how did you do it? Or is my testing strategy completely off?

like image 687
quanticle Avatar asked Feb 25 '16 05:02

quanticle


1 Answers

Your unit test code should not connect to the real Azure DocumentDb.

wrap your Azure client class in an interface, and in the concrete class' method, make the DocumentDB call. this is your real code.

and when you are unit testing the caller class of this method, mock the wrapper interface, inject it into the class being tested and throw a DocumentClientException yourself in the Moq setup. and test the scenario.

Since DocumentClientException only has internal constructors, it is worth having a test method to construct this using reflection. (this is surely a perf-hit, but being test code, you could opt for testability vs. a few milliseconds)

private static DocumentClientException CreateDocumentClientExceptionForTesting(
                                               Error error, HttpStatusCode httpStatusCode)
{
    var type = typeof (DocumentClientException);

    // we are using the overload with 3 parameters (error, responseheaders, statuscode)
    // use any one appropriate for you.

    var documentClientExceptionInstance = type.Assembly.CreateInstance(type.FullName, 
        false, BindingFlags.Instance | BindingFlags.NonPublic, null,
        new object[] {error, (HttpResponseHeaders) null, httpStatusCode}, null, null);

    return (DocumentClientException)documentClientExceptionInstance;
}

And then have callers use them as,

var error = new Error
{
    Id = Guid.NewGuid().ToString(),
    Code = "some_code",
    Message = "some_message"
};

var testException = CreateDocumentClientExceptionForTesting(error, HttpStatusCode.InternalServerError);

// make Moq throw testException
like image 109
Raja Nadar Avatar answered Oct 23 '22 11:10

Raja Nadar