私はモックフレームワークとしてMoqを使用しています。2つの異なるメソッドを実行したいという状況があります。どちらもメソッドをインターフェースと呼びます。両方のメソッドが、インターフェイス上でまったく同じメソッドを同じ順序で同じパラメーターで呼び出すことを確認したいと思います。説明のために、ここにコードがあります:
[TestMethod]
public void UnitTest()
{
var classToTest = new ClassToTest();
Mock<IMyInterface> mock1 = new Mock<IMyInterface>();
// Setup the mock
Mock<IMyInterface> mock2 = new Mock<IMyInterface>();
// Setup the mock
classToTest.MethodToTest(mock1.Object);
classToTest.DifferentMethodToTest(mock2.Object);
// here I need help:
mock1.Verify(theSameMethodsAsMock2);
}
たとえば、IMyInterface
2つのメソッドがMethod1(int i)
ありMethod2(string s)
、、の場合MethodToTest
、構造があればテストに合格する必要があります
void MethodToTest(IMyInterface x)
{
x.Method1(42);
x.Method2("example");
x.Method1(0);
}
そしてDifferentMethodToTest
そのように見えます:
void MethodToTest(IMyInterface x)
{
int a = 10 + 32;
x.Method1(a);
string s = "examples";
x.Method2(s.Substring(0, 7));
x.Method1(0);
// might also have some code here that not related to IMyInterface at all,
// e.g. calling methods in other classes and so on
}
同じ順序、同じメソッド、同じパラメータ。これはMoqで可能ですか?または、別のモックフレームワークが必要ですか?
私は自分で解決策を見つけましたInvocationAction
:
[TestMethod]
public void Test()
{
var classToTest = new ClassToTest();
var methodCalls1 = new List<string>();
var invocationAction1 = new InvocationAction((ia) =>
{
string methodCall = $"{ia.Method.Name} was called with parameters {string.Join(", ", ia.Arguments.Select(x => x?.ToString() ?? "null"))}";
methodCalls1.Add(methodCall);
});
Mock<IMyInterface> mock1 = new Mock<IMyInterface>();
mock1.Setup(x => x.Method1(It.IsAny<int>())).Callback(invocationAction1);
mock1.Setup(x => x.Method2(It.IsAny<string>())).Callback(invocationAction1);
// Same for mock2 ...
classToTest.MethodToTest(mock1.Object);
classToTest.DifferentMethodToTest(mock2.Object);
CollectionAssert.AreEqual(methodCalls1, methodCalls2);
}
コード、特に文字列の比較が非常に不器用であることは知っていますが、当面はそれで十分です。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加