EF4.1 DbSet vs. EF4 ObjectContext and Unit Testing

独自空忆成欢 提交于 2020-01-04 05:21:19

问题


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.


回答1:


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:

  • ASP.NET MVC3 and Entity Framework Code first architecture
  • Organizationally, where should I put common queries when using Entity Framework Code First?


来源:https://stackoverflow.com/questions/6407164/ef4-1-dbset-vs-ef4-objectcontext-and-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!