检查两个不同的方法是否在模拟对象上调用相同的方法

Check that two different methods call the same methods on mocked object

我正在使用 Moq 作为模拟框架。我有一种情况,我想执行两种不同的方法,这两种方法都调用接口的方法。我想确保这两种方法在我的界面上以相同的顺序和相同的参数调用完全相同的方法。为了说明,这里是代码:

[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 有两个方法,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
}

相同的顺序,相同的方法,相同的参数。最小起订量有可能吗?或者我需要另一个模拟框架吗?

我自己找到了一个解决方案,它使用 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);
}

我知道代码很笨拙,尤其是字符串比较,但暂时够用了。