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 部分が削除されているようです

今、私は変わりました

Expect.Call(デリゲート { myFooObject.Getvalue(5, null); })。Do(新しい GetValueDelegate(GetValue)).IgnoreArguments() .Repeat.Any();

Expect.Call(delegate { myFooObject.Getvalue(5, null); }).IgnoreArguments(). Do(新しい 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 に答える