使用 MBUnit 根据数据库测试值
我需要测试一个类,其返回值取决于数据库中的值。我可以在单元测试中访问数据库,但这些值可能会改变。对此有标准的解决方案吗?
I need to test a class who's return value depends on values from a database. I could just hit the database in the unit test but those values could change. Is there a standard solution to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准答案是重新设计您的类,以便您可以模拟依赖关系。这通常是通过将数据源作为接口注入到类中来完成的。
例如,您可能有一个如下所示的类
Load 依赖于 SQLCommand,因此您始终需要为此调用 db
如果您注入数据源接口,您将拥有更大的灵活性
,例如
现在,如果您不能/不会这样做,您必须将此测试视为集成测试。你为它设置数据怎么样?例如插入您想要读取的行。然后将数据恢复到原始状态。这样做的缺点是你的测试会缓慢且脆弱。
The standard answer is to redesign you class so you can mock out the dependency. This is typically done by injecting your datasource as an interface into you class.
e.g. You may have a class that acts like below
Load is dependent on the SQLCommand so you will always need to call a db for this
If you inject a datasource interface you have more flexibility
e.g.
Now if you cannot/will not do that you must treat this test as an integration test. How about you set up data for it. e.g. insert the row you are wanting to read. Then return the data to its original state. The down side to this is that your test will be slow and brittle.