Matthew Knudsen
Matthew Knudsen

Reputation: 213

.NET Web API Unit testing with Moq entity framework

I'm not very familiar with the Moq entity framework or web api testing. Would it be correct to say that the Moq framework does not exercise the controller logic? It seems to me that the moq allows you to setup entities as expected results and parameters. Then you can simply verify that the correct method is called.

example. Lets say I have an apicontroller, that contains a method with the signature of:

public int GetEntity(string id)
{
    return myRepository.Get(id);
}

And lets say the interface looks like this:

public Interface IRepository
{
     public int Get(int id);
}

And the implementation of said interface looks like this:

public class myRepository : IRepository
{
   public int Get(int id)
   {
       if(id == null)
       {
           throw some exception();
       }
       // more logic here
       // maybe I fetch some data from a data source
    }
 }

So the moq framework allows me to make an instance of my repository.

Mock<IRepository> mockRepo = new Mock<IRepository>();
// some setup
this.mockRepo.Setup(repo => repo.Get(It.IsAny<int>()).Returns(new int { TotalResults = 1});
// then an assert to ensure I got the expected number of results.

It seems to me that this doesn't exercise the myRepository code. Is that correct or incorrect? If I'm not exercising the logic in myRepository what am I really validating here? this seems to be a good way to relieve me from hosting the service locally. beyond that I'm not sure how useful this is.

Upvotes: 1

Views: 1079

Answers (1)

oleksii
oleksii

Reputation: 35925

You need to figure out what your unit under test (uut) is. If it is a controller then repository doesn't matter. Unit test should always test a single unit and a single piece of functionality of that unit. Another point to make is that once you start hosting a service, you no longer have a unit test - it will become an integration test. Integration test is a lot harder to write and maintain.

To your questions

It seems to me that this doesn't exercise the myRepository code. Is that correct or incorrect?

Correct. It should not exercise it, because your uut is controller, therefore you mock/stub/fake everything else.

If I'm not exercising the logic in myRepository what am I really validating here?

You can validate that controller has correct state or behaviour, for example input validation or that controller calls correct method of a given repository.

Upvotes: 2

Related Questions