我正在尝试验证,我的moq模拟对象中的方法将在两次连续的API调用中被调用。每次都有不同的参数。
这可能吗?
e.g。我希望我的代码看起来像这样:
mock.Verify(mock => mock.Display(firstColor));
mock.Verify(mock => mock.Display(secondColor));
Assert.AreNotEqual(firstColor, secondColor);
答案 0 :(得分:2)
需要将所有传递的参数收集到List<string> colours
变量中,以便能够验证它们。
[TestMethod]
public void MethodCallsTest()
{
// arrange
var mock = new Mock<IObjectToMock>();
var colours = new List<string>();
mock
.Setup(it => it.Display(It.IsAny<string>()))
.Callback<string>(colour => colours.Add(colour));
// act
/* Any code that invokes method 'Display'.
Direct call the method is the simplest way to test. */
mock.Object.Display("red");
mock.Object.Display("green");
// assert
colours.Count.Should().Be(2);
/* Any assertions that are needed */
colours.ForEach(colour => mock.Verify(it => it.Display(colour)));
Assert.AreNotEqual(colours[0], colours[1]);
}
public interface IObjectToMock
{
void Display(string colour);
}