Friday, August 26, 2016

Mocking Entity Framework Database Transactions

If you are writing Unit Tests for any of your classes that leverage Entity Framework, you should be able to Mock most operations leveraged by Entity Framework.

However, Entity Framework 6 introduces features for wrapping your operation in a BeginTransaction() statement as described here:

The problem with this scenario, of course, is that this code cannot easily be Mocked!

Well, what do you do in these scenarios?

Well, first of all, I would recommend looking at the use case scenarios to determine if you really need this functionality since Microsoft describes this in the article:

In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.

Therefore, transactions are being used as required by Entity Framework for insert, update and delete operations!!

If you read articles such as this which does some additional examination on the repercussions of using Entity Framework Database Transactions (, you will see that the recommendation is to NOT USE Entity Framework Database Transactions (especially with Web Applications).

Therefore, unless the business logic ABSOLUTELY requires the use of Entity Framework Database Transactions in this manner, you can probably safely remove this code and thereby save yourself a great deal of hassle while writing your Unit Tests!!

No comments:

Post a Comment