How to effectively Unit Test a DAL that uses ADO.NET and SQL Server with NUnit?

有些话、适合烂在心里 提交于 2019-12-04 08:05:40

What exactly would those unit tests test? Considering typical DAL code is rarely anything more than delegating actual work to 3rd party data access code (ADO.NET, EntityFramework, NHibernate).

I haven't used ADO.NET much, but I suppose this NHibernate example is sufficient enough:

public User GetUser(int id)
{
    using (var session = sessionFactory.OpenSession())
    {
        return session.Get<User>(id);
    }
}

Of course, assuming the code is wrote correctly, all the dependencies (sessionFactory namely) would be passed via interfaces and therefore easy to stub, so writing unit test is possible (you'll just have to mock a lot of stuff to make it happen).

Purist approach would be to write such unit test, as it's yet another data point proving your code indeed does what you assume (calling Get). However, note that test like this is rather expensive, as you essentially have to stub entire database access made by your provider (mocking sessionFactory to return mocked session which is then checked for calls made).

This is difficult decision to be made (whether follow purist approach in this case), as you will have to write integration tests with real database anyways. And those tests will cover exactly the same areas as unit tests you'd wrote, but working in real environment (instead of stubbed one).

In my experience, unit testing DAL is usually not worth the benefits it offers, especially when contrasted with its rather high costs (time spent writing code to stub the database environment) for unit test) and existence of proper integration tests suite.

And last, I would advise against using in-memory database in any kind of testing. For the reasons below:

  • it is slow
  • it has several possible failure points that may be difficult to control (ORM configuration, in-memory database setup, possibly invalid test data)
  • gives you false sense of doing integration testing (while you're not; in-memory database might behave entirely different than your real, production one)

Unless you can load up exactly the same database to the memory, stick to proper integration tests (that would be DAL testing priority) with isolated unit tests backup (only if you can afford to write them).

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