Wednesday 18 March 2015

Mocking DbContext and unit tests / integration tests

            Recently I've been preparing some integration and unit tests for a repository class that was using DbContext inside. Had to mock the DbContext to return a specific list of entities for each case.
For some reason I kept on getting the following error each time I've tried to run them:


The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.


It turned out that because I wasn't using Ef6 code anywhere explicitly, its use wasn't registered and the dll wasn't being loaded causing the above error. All that was required was calling something from inside of the Ef6 dll in some class.


Decided to use the static constructor of my DbContext derived class.


public class MyDbContext : DbContext
{
    static MyDbContext()
    {
        var efUsageHack = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
    }
}


Finding out the reason and solution took a bit of searching, for example here: http://robsneuron.blogspot.com/2013/11/entity-framework-upgrade-to-6.html