0

In entity framework, DBContext is not thread-safe. In order to support multi-thread environment, I had to initialize a new DbContext based on a connection string every time a communication with SQL is needed.

private void function(string sqlConnectionString)
{
    using (var dbContext = new DbContext(sqlConnectionString))
    {
        // talk to sql here
    }
}

Now the unit test becomes tricky. Since DbContext is buried in the code, there is no way for me to pass in a mocked DbContext.

I looked online but didn't find a good solution. Any suggestions?

Sudipta Mondal
  • 2,550
  • 1
  • 19
  • 20
checai
  • 836
  • 4
  • 11
  • 17

1 Answers1

1

To unit test this, I would create a factory for the DbContext and get the factory injected. The factory could now be Substituted with NSubstitute. For the unit tests part the substituted DbContext factory would return a new DbContext with a connection to a memory database such as Effort for Entity Framework

private void function(IDbContextFactory dbContextFactory)
{
    using (var dbContext = dbContextFactory.Create())
    {
        // talk to sql here
    }
}

In the code of your unit test:

//Arrange
var connectionStringForEffortDatabase = ...
var dbCotextFactory = Substitute.For<IDbContextFactory>();
dbContextFactory.Create().Returns(new DbContext(connectionStringForEffortDatabase));

//Act
function(dbContextFactory);

//Assert
Assert.Something():
Jogge
  • 1,654
  • 12
  • 36