When unit testing, do you have to use a database to test CRUD operations?

后端 未结 7 1006
广开言路
广开言路 2021-02-09 21:11

When unit testing, is it a must to use a database when testing CRUD operations? Can sql lite help with this? Do you have to cre-create the db somehow in memory?

I am usi

7条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 21:20

    As with all complicated question, the answer is: It depends :)

    In general you should hide your data access layer behind an interface so that you can test the rest of the application without using a database, but what if you would like to test the data access implementation itself?

    In some cases, some people consider this redundant since they mostly use declarative data access technologies such as ORMs.

    In other cases, the data access component itself may contain some logic that you may want to test. That can be an entirely relevant thing to do, but you will need the database to do that.

    Some people consider this to be Integration Tests instead of Unit Tests, but in my book, it doesn't matter too much what you call it - the most important thing is that you get value out of your fully automated tests, and you can definitely use a unit testing framework to drive those tests.

    A while back I wrote about how to do this on SQL Server. The most important thing to keep in mind is to avoid the temptation to create a General Fixture with some 'representative data' and attempt to reuse this across all tests. Instead, you should fill in data as part of each test and clean it up after.

提交回复
热议问题