Simple Moq

I recently worked on a project in which 90% of its tests were integration tests because the core purpose of the project was to interact with external entities. In an effort create more unit tests, I employed Moq (and lots of refactoring).  This is an example of basic Moq usage.

Let’s say we have a repository that gets documents from a database.  The assumption is that a repository interface, IDocumentRepository, is being implemented.

In my case, I found it easier to deserialize results from file, rather than building the results by hand for each mocked response.  I used System.Xml.Serialization to serialize real responses to file.

Let’s Moq it…

var mockRepository = new Mock<IDocumentRepository>();

// if the query is for text/plain documents only, mock a response for that
mockRepository.Setup(p => p.FindDocuments(
    It.Is<DocumentQueryParams>(q => q.MimeType == "text/plain")))
// use It.IsAny to return the same result regardless of the parameters
mockRepository.Setup(p => p.FindDocuments(