Jmaurier
Jmaurier

Reputation: 847

How can I use Moq to test a method that creates a new DbContext?

I'm using: MSTest, Entity Framework 6, and Moq

I'm trying to learn TDD with our preexisting entity framework asp.net application. Right now I'm working in our web api, I created a fresh test project and class and I'm trying to write a test just to see if I can get at least one value back. So in some places I am obviously having to write tests for code that is already in place.

Here I can't figure out if/how to set up my test project, class, or method (not sure which needs setup) in order to test this method

[HttpGet]
[ResponseType(typeof(IEnumerable<TimeZoneDTO>))]
[Route("api/timezone")]
public IHttpActionResult GetTimeZones()
{
    var _out = new IEnumerable<TimeZoneDTO>();
    using (var db = new Entities())
    {
        _out = from x in db.Timezones
               orderby x.UTCOffSet descending
               select new TimeZoneDTO() {
                   Caption = x.Name,
                   Id = x.Abbreviation
               };
    }

    return Ok(_out);
}

The problem is that using (var db = new Entities()) is dependent on a named database configuration string in the web.config file of the controller's project.

public partial class Entities : DbContext
{
    public Entities(): base("name=Entities") {}

    ...
}

What are my options here? Is there a way to get Moq to handle this or do I need to update the test project somehow? What I don't want to do (at this point) is rework something that is going to make me have to change other core parts of the application.

Upvotes: 0

Views: 582

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156524

The typical way to handle situations like this is to change the class that you're testing so that it injects either the DbContext itself or a factory that produces the DbContext. That way, rather than newing up the DbContext on its own, it relies on the Dependency Injection configuration to determine how the DbContext is created. Then you can mock the DbContext (using a mock or fake factory, if you go the Factory route).

Upvotes: 1

Related Questions