在 asp.net mvc 中测试上下文

发布于 2024-08-26 21:13:39 字数 156 浏览 5 评论 0原文

我在测试控制器方面很有经验,但我的问题是,我们是否也应该测试数据上下文,以及如何测试?我的意思是,来自数据库的许多关系和约束是简单测试控制器无法涵盖的。

另一方面,针对数据库进行测试并不被认为是一个好的实践——然后呢?简单地测试没有 db.SubmitChanges() 或者什么?

I got pretty experienced with testing controllers, my question here is though, aren't we supposed to test the data context as well, and how ? I mean, there are a lot of relationships and constraints coming from the DB that simply testing controllers does not cover.

On the other hand, testing against the DB is not considered a good practice - what then ? Simply testing without db.SubmitChanges() or what ?

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

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

发布评论

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

评论(3

热血少△年 2024-09-02 21:13:39

恕我直言,您不应该测试 DataContext。希望微软已经做到了这一点,因此测试 SubmitChanges 将数据保存到数据库中对我来说毫无意义。您应该进行集成或 Web 测试,在其中定义特定场景并验证应用程序的输出。

IMHO you should not test the DataContext. Hopefully Microsoft have already done this, so testing that SubmitChanges will persist data into the DB is pointless for me. You should do integration or web testing where you would define a specific scenarios and verify the output from the application.

世界和平 2024-09-02 21:13:39

在测试存储库时,典型的方法是创建一个内存数据库,每次运行测试时都可以拆除并重建该数据库。通过使用这种方法,您将始终知道数据是什么样子,以便您可以更轻松地对其进行断言。此外,您不会接触到您的真实数据,这始终是一个积极的方面。 Sqlite 是 .NET 领域中最受欢迎的一种。

When it comes to testing your repositories, the typical approach is to create an in-memory database that can be torn down and rebuilt for each time you run your tests. By using this approach, you will always know what the data will look like so you can more easily make assertions against it. In addition, you won't be touching your real data, which is always a positive. Sqlite is the most popular one out there in the .NET space for this.

巾帼英雄 2024-09-02 21:13:39

是的,您应该对数据上下文进行集成测试,以确保您放入数据库本身的任何“代码”都能正常工作——唯一性约束、触发器等。这并不意味着您应该这样做但是,对数据库进行单元测试。话虽如此,您放入模型类中的任何代码都应该经过单元测试。通常,您无需直接针对数据库进行测试即可执行此操作。例如,任何验证代码都应该能够运行,而不需要您实际插入或更新数据库。

Yes, you should do integration testing of your data context to ensure that any "code" that you put in the database itself works -- uniqueness constraints, triggers, etc. This doesn't imply that you should do your unit testing against the database, however. Having said that, any code you put in your model classes should be unit tested. Usually, you can do this without having to test against the database directly. For example, any validation code should be able to run without requiring that you actually insert or update the DB.

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