如何对持久性进行单元测试? [英] How do I unit test persistence?

查看:42
本文介绍了如何对持久性进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为实践测试驱动开发的新手,我经常陷入困境,即如何对数据库的持久性进行单元测试.

As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database.

我知道从技术上讲这将是一个集成测试(而不是单元测试),但我想找出以下方面的最佳策略:

I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following:

  1. 测试查询.
  2. 测试插入.如果插入失败,我怎么知道它出错了?我可以通过插入然后查询来测试它,但是我怎么知道查询没有错呢?
  3. 测试更新和删除——与测试插入相同

执行这些操作的最佳做​​法是什么?

What are the best practices for doing these?

关于测试 SQL:我知道这可以完成,但是如果我使用像 NHibernate 这样的 O/R 映射器,它会在用于输出查询的别名中附加一些命名疣,因为这有点不可预测,我我不确定我是否可以对此进行测试.

Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that.

我应该放弃一切,只相信 NHibernate 吗?我不确定这是否谨慎.

Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent.

推荐答案

查看 DB 单元.它是一个 Java 库,但必须有一个 C# 等效项.它可以让您使用一组数据准备数据库,以便您知道数据库中的内容,然后您可以与 DB Unit 交互以查看数据库中的内容.它可以在许多数据库系统上运行,因此您可以使用实际的数据库设置,或使用其他东西,例如 Java 中的 HSQL(具有内存选项的 Java 数据库实现).

Look into DB Unit. It is a Java library, but there must be a C# equivalent. It lets you prepare the database with a set of data so that you know what is in the database, then you can interface with DB Unit to see what is in the database. It can run against many database systems, so you can use your actual database setup, or use something else, like HSQL in Java (a Java database implementation with an in memory option).

如果您想测试您的代码是否正确使用了数据库(您很可能应该这样做),那么这是隔离每个测试并确保数据库准备好预期数据的方法.

If you want to test that your code is using the database properly (which you most likely should be doing), then this is the way to go to isolate each test and ensure the database has expected data prepared.

这篇关于如何对持久性进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆