如何模拟带有参数的 void 方法并更改值参数?
我想测试一个依赖于另一个类(SomeClassB)的类(SomeClassA)。我想模拟 SomeClassB。
public class SomeClassA
{
private SomeClassB objectB;
private bool GetValue(int x, object y)
{
objectB.GetValue(x, y); // This function takes x and change the value of y
}
}
SomeClassB 实现接口 IFoo
public interface IFoo
{
public void GetValue(int x, SomeObject y) // This function takes x and change the value of y
}
pulic class SomeClassB : IFoo
{
// Table of SomeObjects
public void GetValue(int x, SomeObject y)
{
// Do some check on x
// If above is true get y from the table of SomeObjects
}
}
然后在我的单元测试类中,我准备了一个模仿 SomeClassB.GetValue 的委托类:
private delegate void GetValueDelegate(int x, SomeObject y);
private void GetValue(int x, SomeObject y)
{ // process x
// prepare a new SomeObject obj
SomeObject obj = new SomeObject();
obj.field = x;
y = obj;
}
在模拟部分我写道:
IFoo myFooObject = mocks.DynamicMock();
Expect.Call(delegate { myFooObject.Getvalue(5, null); }).Do(new GetValueDelegate(GetValue)).IgnoreArguments().Repeat.Any();
SomeObject o = new SomeObject();
myFooObject.getValue(5, o);
Assert.AreEqual(5, o.field); // This assert fails!
我检查了几个帖子,委托似乎是模拟 void 方法的关键。但是,在尝试了上述方法后,它不起作用。您能否告知我的委托课程是否有任何问题?还是模拟语句中有问题?
我的 RhinoMocks 是 3.5,如果我包含 IgnoreArguments() 似乎它正在删除 Do 部分我刚刚找到这个页面: http: //www.mail-archive.com/rhinomocks@googlegroups.com/msg00287.html
现在我变了
Expect.Call(delegate { myFooObject.Getvalue(5, null); })。Do(new GetValueDelegate(GetValue)).IgnoreArguments().Repeat.Any ();
至
Expect.Call(delegate { myFooObject.Getvalue(5, null); }).IgnoreArguments()。做(新的GetValueDelegate(GetValue)) .Repeat.Any();
现在它工作得很好!