2

I currently have a project I've started with EF4, and am going back and adding in unit testing after the fact. I am using the EF4 POCO T4 templates with my model (database) first context. I am using generic repositories for my DAC logic, and unit of work pattern for persistence.

However, I'm running into some issues understanding how to mock up the ObjectContext/ObjectSet. I looked at using the FakeObjectSet<T> sample from this article, but it still leaves a few things out, such as auto-incrementing identities and transaction rollbacks.

So, I'm trying to find a good EF design that will still be fully unit testable.

My question is, does EF4.1 DbSet solve a lot of the issues w/ unit testing EF4? Are there any good comprehensive articles for designing EF4.1 solutions that are fully testable?

Also, keep in mind that I need a model-first solution.

Thanks in advance.

Jerad Rose
  • 14,405
  • 16
  • 78
  • 150

1 Answers1

6

Fully simulating behavior of mocked layer is not point of unit testing. The point of unit testing is believing that mocked layer simply works. Unit test verifies the tested method not the mock. You will just verify that correct method on the mock were called and perhaps you will set up some callbacks for modifying passed data if your business logic expects some values. Example:

You have a business method inserting the record to the database and using the entity and its Id after insertion. The IObjectSet mock will be configured to:

  • Set expectation that AddObject was called only once - you can set the expected instance in the verification
  • You can define callback for AddObject to set Id to some value and use it later in the test

DbSet will not make any difference - it is just wrapper around ObjectSet with similar behavior. In my opinion there is no efficient way to make mocks behave as real EF. The effort needed for creating mock with behavior simulating EF + database will be much bigger then effort for your whole application! That will not be mock anymore it will be fake EF provider.

If you want to test your EF code (mapping, querying, persisting) and database behavior (like auto-increment, transactions, etc) you have to write integration tests. Here you have some related questions discussing repositories, unit of work and challenges with testing:

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • Thanks for your response, that made a lot of sense. I'm fairly green to TDD, so some of these concepts are still sinking in. Your post helped a lot of things come together for me. – Jerad Rose Jun 20 '11 at 14:27