パラメータを使用して 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();
そして今、それは完全に正常に動作します!