Mocking out nHibernate QueryOver with Moq

前端 未结 5 2020
终归单人心
终归单人心 2021-01-04 20:41

The following line fails with a null reference, when testing:

var awards = _session.QueryOver().Where(x => x.BusinessId == (int)business).List         


        
5条回答
  •  春和景丽
    2021-01-04 20:58

    This is not a good idea. You should not mock the types you don't own. Instead you should introduce a Repository, base its interface on domain/business language and implement it using NHibernate. Implementation can use ICriteria, HQL, QueryOver, Linq etc. The point is that this decision will be encapsulated and hidden from the code that consumes repository.

    You can write an integration test that will test combination of your interface + Real ORM + Real or Fake database. Please take a look at this and this answers about testing repositories and data access. Testing the code that uses Repository is also super easy because you can mock Repository interface.

    What are the advantages of this approach other than testability? They are somewhat related to each other:

    • Separation of Concerns. Data access issues solved in the data access layer (repository implementation).
    • Loose Coupling. The rest of the system is not coupled to the data-access-tool-of-the-day. You have potential for switching repository implementation from NHibernate to raw sql, azure, web service. Even if you never need to switch, the layering is enforced better if you design 'as if' you need to switch.
    • Readability. Domain objects, including repository interface definition are based on business/domain language.

提交回复
热议问题