【发布时间】:2013-06-11 18:41:02
【问题描述】:
我想问在下一个示例中如何使用 rhino mocks:
Public Class CustomerService
{
Public void Register()
{
Action1();
Action2();
}
private action1 ()
{
//this is a call to other dll.
var isExist = _dataComponentService.CheckIfUserExist(userName);
}
private action2()
{
//do some more work...
// Call to dataComponentService. write some data in the database....
}
}
这只是我需要更新的真实代码的一个示例。 当前的单元测试正在对数据库服务进行真正的调用。 我想编写一个单元测试来检查公共 Register() 中的行为,而无需真正调用数据库服务。
是否可以模拟对位于私有方法中的其他组件的调用,而无需重新编写漏洞服务?
谢谢你
原产地
【问题讨论】:
-
您应该使用依赖注入将
dataComponentService对象提供给CustomerService类。我推荐构造函数注入。在应用程序运行时dataComponentService被设置为真实的数据库访问实例,但在测试场景中您可以使用模拟对象。网上有很多关于 DI with unit test 的文章,例如 Mark Seemann 的博客:link。
标签: c# .net unit-testing mocking rhino-mocks