Search code examples
c#mockingfakeiteasy

Mocking with FakeItEasy and DBContext does not work


Why is this test code not working?

Methode CheckDbAsync() in test-Class:

public async Task<bool> CheckDbAsync()
{
return await DbContext
                    .GetDatabase()
                    .CanConnectAsync(default);
}   

Testcode with FakeItEasy:

var dbContext = A.Fake<IDbContext>();
           
A.CallTo(() => dbContext
                .GetDatabase()
                .CanConnectAsync(default))
                .Returns(Task.FromResult(true));


var tc= new Testclass(dbContext);

bool result=await tc.CheckDbAsync();

Always returns false, not true.


Solution

  • What're IDbContext and GetDatabase? I can't find references to these things. Maybe because I'm not an EntityFramework user and maybe because they're your own things? It's helpful to have more context when answering these questions.

    There's not a lot to go on here, but I'll guess:

    GetDatabase is returning a different object every time you call it. This is the standard behaviour for unconfigured methods that FakeItEasy fakes.

    So you configure one whatever-the-return-type-of-GetDatabase-is, and then another one is used within CheckDbAsync.

    To verify, you can check the objects for reference equality. To remedy, you probably want to configure dbContext.GetDatabase to always return the same whatever-the-return-type-of-GetDatabase-is.

    (An alternative cause for the observed behaviour: there's no connection between dbContext in the test class and DBContext in the production code. We see you pass dbContext into the Testclass constructor, but we don't know what happens to dbContext after that. Or even if the CheckDbAsync method is part of the same Testclass class. I imagine it is, and that you just store the dbContext in the DbContext property, but I can't tell for sure, and thought I'd mention it, just in case that's the real problem.)