Search code examples
entity-frameworkunit-testingef-model-builder

In Entity Framework how do I unit test dbmodel construction without actually connecting to a db?


I have a class inheriting from DbContext implementing a code-first Entity Framework object.

I would like to have a unit test that exercises the model builder in this dbcontext -- this would be useful for detecting things like 'key not defined on entity' errors.

But I may not have an actual database available during unit testing time. Is there a way to exercise this code without actually trying to make a database connection with the context. I tried something innocuous like:

var ctx = new MyDbContext("Data Source=(local);Initial Catalog=Dummy;<.......>");
var foo = ctx.GetValidationErrors();  //triggers DBModelBuilder, should throw if my DBModel is goofed up

This does technically work. However this takes a very long time to run -- if I pause and inspect the call stack it is triggering a call to System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin

Eventually it times out, swallows the connection error and finishes my test.

Is there any way to do this without the connection attempt?


Solution

  • The solution here is to just kind of go with the problem and use the lowest possible connection timeout. I'm using this connection string:

    Server=localhost; Database=tempdb; Integrated Security=true;Connection Timeout=1;ConnectRetryCount=0

    It still triggers the problem, but with a one second timeout and no automatic retries (for only this one test in the system) it's totally acceptable.

    And if the developer has a local db installed, it will accidentally work even faster.