1

如何模拟带有参数的 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();

现在它工作得很好!

4

1 回答 1

4

Kar,您使用的是真正的旧版本 .NET 还是什么?这种语法已经过时了很长一段时间。我也认为你做错了。Rhino Mocks 并不神奇——它不会做任何你用几行额外代码自己做不到的事情。

例如,如果我有

public interface IMakeOrders {
  bool PlaceOrderFor(Customer c);
}

我可以通过以下方式实现它:

public class TestOrderMaker : IMakeOrders {
  public bool PlaceOrderFor(Customer c) {
    c.NumberOfOrders = c.NumberOfOrder + 1;
    return true;
  }
}

或者

var orders = MockRepository.GenerateStub<IMakeOrders>();
orders.Stub(x=>x.PlaceOrderFor(Arg<Customer>.Is.Anything)).Do(new Func<Customer, bool> c=> {
    c.NumberOfOrders = c.NumberOfOrder + 1;
    return true;  
});

阅读我为一些承包商编写的RM 简介。

于 2010-04-21T01:29:09.897 回答