Typemock Isolator: How to mock a DbContext that is not injected?

260 Views Asked by At

I'm testing my repositories in a Asp.Net MVC project and I need to mock a DbContext for my Unit Tests. DbContext is not injected and I can't change the code.

I checked this answer out and I followed it step by step but it didn't work. This is my code, I tried to simplify it:

    [TestMethod]
    public void SaveAmountsAfterCalculation()
    {
        // Faking the Context
        var fakeContext = Isolate.Fake.NextInstance<MyContext>();
        Isolate.WhenCalled(() => new MyContext()).WillReturn(fakeContext);

        // Faking one the the DbSetList of the Context
        Isolate.WhenCalled(() => fakeContext.SomeDbSet)
        .WillReturnCollectionValuesOf(somehtingElseList);

        // Calling the method to test
        MyRepository.SaveAmountsAfterCalculation();

        // Verifying if SomeProperty was called
        Isolate.Verify.WasCalledWithAnyArguments(() => fakeContext
        .SomeProperty.Attach(null));
    }

When the context is created within using statement, no exception is thrown.

using (var ctx = new MyContext())
{
   ...
   // The exception is thrown here.
   if (ctx.SomeDbSet.Any(...))
   ...
}

but if I inspect any property (DbSet) then I can see this error: No connection string named 'MyContext' could be found in the application config file.. I already added a connection string to my Test project, but it didn't work either. The moment that SomeDbSetis called, then the Exception is thrown even when I told TypeMock to replace the result of that method with somethingElse. See the code above.

1

There are 1 best solutions below

2
JamesR On

It looks like the line "Isolate.WhenCalled(() => new MyContext()).WillReturn(fakeContext);" is obsolete and perhaps causing your problem because you already faked the call "new MyContext()" when you used fakeNextInstance.