0

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?

Clyde
  • 8,017
  • 11
  • 56
  • 87

1 Answers1

0

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.

Clyde
  • 8,017
  • 11
  • 56
  • 87
  • 1
    If you use actual database, then it is not unit testing, but integration testing. – DixonD Feb 05 '15 at 20:53
  • I'm not sure you understood the question. The whole point is to validate the DB Model code without connecting to a database. This is certainly not an integration test. If you have ideas for executing this test without a dummy connection attempt, that would be awesome! – Clyde Feb 05 '15 at 20:56