验证使用参数列表调用的方法,每次一次?

Verify method called with list of parameters, one time each?

我有一个测试,其中有一组参数,我想验证该方法是否被调用并且每个参数都被恰好指定了一次。我可以这样做:

var paramList = new List<string> { "one", "two", "three", "four" };
paramList.ForEach(x => MyMock.Verify(y => y.DoSomething(x), Times.Once));

但我想知道 Moq 是否提供了我只需一次验证调用即可完成的操作。

如果我没记错的话,我认为 moq 不会提供。问题是,即使您使用 Verifiable 进行了正确设置以使用 Verify,或者如果您想使用 VerifyAll,您也无法指定 Times 限制。


验证

paramList.ForEach(s => mock.Setup(m => m.DoSomething(s)).Verifiable());

mock.Object.DoSomething("one");
mock.Object.DoSomething("two");
mock.Object.DoSomething("three");
mock.Object.DoSomething("four");

mock.Verify(); //Cannot specify Times

全部验证

paramList.ForEach(s => mock.Setup(m => m.DoSomething(s)));

mock.Object.DoSomething("one");
mock.Object.DoSomething("two");
mock.Object.DoSomething("three");
mock.Object.DoSomething("four");

mock.VerifyAll(); //Cannot specify Times

不过,我没有发现您的方法有任何问题,我只是想再添加一个选项。你可以通过使用 Capture.In 功能来避免 Verify,像这样:

//Arrange
var invocation = new List<string>();
mock.Setup(m => m.DoSomething(Capture.In(invocation)));

//Act
mock.Object.DoSomething("one");
mock.Object.DoSomething("two");
mock.Object.DoSomething("three");
mock.Object.DoSomething("four");

//Assert
CollectionAssert.AreEquivalent(paramList, invocation);