Sparafusile
Sparafusile

Reputation: 4956

Exception thrown when accessing DBContext from unit test

Any unit test the includes a call to SELECT (using LINQ) data from my DBContext throws the following error:

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

Doing a search for that specific error leads me to believe that I need to include the following line in my Global.asax Application_Start method:

System.Data.Entity.Database.SetInitializer<MyDBContext>( null );

This is suppose to fix a similar error when running the application itself. Unfortunately, I don't get this error when I run my application and there doesn't seem to be an Application_Start method for my unit test project. Is there any way to to the unit test project that I'm using a custom database back-end and to ignore any changes that have occurred in it?

I added the unit test project after working on my main project for a while so it's possible I messed it up somehow, but I can't figure out for the life of me what to do. I'm using the built in unit testing in Visual Studio 2010.

Upvotes: 0

Views: 600

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

There are 2 methods that you could use with the VS unit testing framework allowing you to run some code before and after each test and before and after all the tests contained in the file

// Use TestInitialize to run code before running each test 
[TestInitialize()]
public void MyTestInitialize() 
{ 

}

// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup() 
{ 

}

or:

// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext) 
{ 

}

// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup() 
{ 

}

Upvotes: 1

Related Questions