2013-03-08 64 views
2

嘲弄的方法我写,执行逻辑下一个单元测试:生成存根或.NET

SomeObject obj1 = new SomeObject(); 
obj1.SomeMethod(args); 

SomeMethod

public void SomeMethod(*Some Args*){  
    AnotherObject obj2 = new AnotherObject(); 
    Obj2.OtherMethod(); 
} 

在我的测试中我不关心Obj2.OtherMethod()实际上做了什么,我希望测试忽略它。所以我认为生成一个存根会为我修复它,但我不知道如何去做。

+1

你有没有看过Moq或RhinoMocks?这听起来像你想嘲笑Obj2。 – Jamie 2013-03-08 14:31:31

回答

3

下面是一种方法。如果你有一个AnotherObject实现的接口(比如说IAnother,至少AnotherMethod作为一个方法),你的正常执行路径会将AnotherObject的一个实例传递给SomeMethod。

然后进行测试,您可以传递一个实现IAnother接口的模拟对象 - 通过使用模拟框架或自己编码。

所以你必须:

Public void SomeMethod(IAnother anotherObject) 
{  
    anotherObbject.OtherMethod(); 
} 
测试

Public class MyMock : IAnother... 

-

IAnother another = new MyMock(); 
..SomeMethod(myMock) 

,但在真正的代码

IAnother = new AnotherObject()... 

你明白了。