类似的话题已经在The value of high level unit tests and mock objects单元测试是在高的抽象层次
但是讨论的方法,我想描述一个具体情况,问你对我应该怎么写单元测试的意见。
我正在开发一个普通的3层应用程序,它使用实体框架。上述EF,我有两个层次:
- 库:他们直接访问EF ObjectContext的和做所有的CRUD工作(实际上,这些类与T4模板生成)。所有Repository类都有一个适当的接口。
- 经理:他们实现更高级别的业务逻辑,他们不直接访问ObjectContext,而是使用合适的Repository。管理员不知道具体的Repository-implementation,只有界面(我使用依赖注入,并在单元测试中模拟)。
没有进一步的说明,这里是我想编写单元测试的类:
public class PersonManager
{
private IPersonRepository personRepository; // This is injected.
// Constructor for injection is here.
public void ComplexMethod()
{
// High level business logic
bool result = this.SimpleMethod1();
if(result)
this.SimpleMethod2(1);
else
this.SimpleMethod2(2);
}
public bool SimpleMethod1()
{
// Doing some low-level work with the repository.
}
public void SimpleMethod2(int param)
{
// Doing some low-level work with the repository.
}
}
它是用的一个模拟实例化PersonManager
很容易单元测试SimpleMethod1
和SimpleMethod2
PersonRepository
。
但我找不到任何方便的方法来单元测试ComplexMethod
。
你有什么建议我应该怎么做?或者不应该单元测试?也许我不应该使用this
参考ComplexMethod
中的方法调用,而是通过一个接口访问PersonManager
本身,并用一个模拟代替它。
在此先感谢您的任何建议。
为什么你不能测试ComplexMethod?你可能不需要为SimpleMethod 1&2测试设置额外的期望... –