Unit Testing Gotcha with Entity Framework
I have been working with the Entity Framework at work. It has been used to connect with a database for a RESTful ASP.Net Web API service.
Testing the Web API has been interesting to learn about. Originally I decided to test this Web API using Fiddler to do HTTP POSTs to selected URLs and then analyzing the results. It soon became apparent that this method was slow and error prone– making me opt for unit-testing.
I spent a good portion of the day writing the tests, fixing bugs as I found them. Fortunately, the API scope of the API was relatively small and writing most of the tests did not take too long. That is, until I encountered a weird side effect of the C# Entity Framework.
One of the API method tests that made a POST required the use of a database ObjectContextobject to check if the request actually updated the database entities that it should have. The test however was failing, I believe this was due a ObjectContext being created in the unit-test method and another being created in the method being tested. The two differentObjectContexts were out of sync even though they were attached to the same datastore.
The structure of the code that caused the problem was similar to this piece of skeleton code:
It appears that the Entity Framework tries to be “smart” and efficient which means that the update is not synchronized between the ObjectContexts. In order to work around this I was required to call the Refresh() method on the ObjectContext after the call to Post(), like so:
I am not sure if this is the recommended way to work around this but it works and the test will pass as you expect. I will look into this more when I get back to the code at work. I will post any new findings or corrections.