如何正确地对我的 DAL 进行单元测试?

发布于 2024-07-08 14:30:19 字数 96 浏览 7 评论 0原文

我是单元测试的新手。 但是,如何对使用实体框架编写的 DAL 进行单元测试,以便确保我的 DAL 代码正常工作,但实际上没有触及任何数据库? 有人可以提供尽可能详细的信息吗?

I'm new to unit testing. But how do I unit test my DAL which is written with Entity Framework, so I can make sure my DAL code is working correctly but no database is actually touched? Could someone give as much detail as possible please.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

她比我温柔 2024-07-15 14:30:19

如果您想测试数据访问层是否正常工作,您确实需要在某个时候针对数据库进行测试,否则您实际上并没有测试它的工作情况。

If you want to test that your data access layer works correct you really need to test it against a database at some point as otherwise you aren't actually testing it works.

无戏配角 2024-07-15 14:30:19

DAL 的单元测试是开发中非常常见的令人头痛的问题。 在大多数情况下,我建议您跳过它。

如今,大多数 ORM 都提供某种查询语言,无论是 LINQ 还是 HQL,或者其他风格。 因为正确的单元测试要求您不实际访问数据库,所以您必须模拟 ORM,而这样做是您能想到的最大的痛苦。 在我看来,这不值得。 最终,您只需测试是否在代码中编写了正确的查询; 您根本得不到回归值,并且可以通过检查代码更好地满足您的目的。

不过,我并不是说您不应该测试 DAL 的使用;而是说您不应该测试 DAL 的使用情况。 只是不要尝试单元测试。 您仍然应该对您的程序/系统进行一套集成和用户验收测试; 让那些人来处理测试您的数据访问。

Unit testing a DAL is a very common headache in development. For the most part, I suggest you skip it.

Most ORMs these days offer some sort of query language, be it LINQ or HQL, or some other flavor. Because a proper unit test requires that you not actually hit the database, you have to mock the ORM and doing that is the biggest pain in the ass you can think of. It's not worth it, IMO. Ultimately, you only end up testing that you wrote the proper query in your code; you get no regression value at all and can better serve your purposes by inspection of the code.

I'm not saying you shouldn't test your use of the DAL, however; just don't try unit testing. You should still have a suite of integration and user acceptance tests for your program/system; let those handle testing your data access instead.

海风掠过北极光 2024-07-15 14:30:19

当我对 DAL 进行单元测试时,我在单元测试结束时使用事务和回滚,因此数据库是干净的。

When I unit test my DAL I use transactions and rollback at the end of the unit test, so the db is clean.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文