Mocking a GetAsync()


I’m trying to figure out how to mock a successful and an unsuccessful document retrieval using NSubstitute.

  1. Do I need to mock the ICouchbaseCollection or can I skip that and directly mock the IGetResult?
  2. How do I cause the IGetResult to return a document?
  3. How do I cause it to throw a CouchbaseException for a document not found?


I’m not an NSubstitute user, but I can answer some of this generically.

  1. Typically, you would mock ICouchbaseCollection and pass this into your class under test. Methods on ICouchbaseCollection would return mock IGetResult instances.
  2. When returning the mock IGetResult, provide a mock implementation of ContentAs<T> to return the document.
  3. This will depend on NSubstitute, so I can’t really answer this. Sorry, I’m a Moq guy. But the exception should be thrown directly on the call to GetAsync.

I was able to mock it, but I’m having trouble mocking a CouchbaseException.Context property

If I do this, it throws the exception:

            var collection = Substitute.For<ICouchbaseCollection>();
            collection.GetAsync(keyName).Throws(new CouchbaseException());

But if I try to mock the Context so I could get the status of “key not found”
like: ((dynamic)ex.Context).Status.ToString()
It doesn’t throw the exception and I can’t even access the Status property, just the Message.

        var errorContext = Substitute.For<IErrorContext>();                  

        var collection = Substitute.For<ICouchbaseCollection>();
        collection.GetAsync(keyName).Throws(new CouchbaseException(errorContext));

Any idea?

First, I’d recommend throwing the more precise exception, in this case a DocumentNotFoundException.

This would be the more typical pattern used by your code under test to detect specific error types.

As to why the exception doesn’t throw, I’m not sure, it may be some internal issue within NSubstitute. However, for this scenario instead of mocking IErrorContext I’d just instantiate a KeyValueErrorContext. The problem with that plan, though, is it appears all the setters are currently marked internal. I think this is probably an oversight for unit testing, and they should probably be made public. I’ve filed an issue to this effect:

1 Like

The issue with mocking the specific ErrorContexts should be resolved in the new 3.2.0 release, let me know how it works for you. We ended up making several changes that should make ErrorContexts more usable.


1 Like