Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify two successive method calls invoke mock method with a different parameters at each time

I'm trying to verify that, a method in my moq mock object will be called upon two successive API calls. And each time with a different parameter.

Is that possible?

e.g. I want my code look like this:

mock.Verify(mock => mock.Display(firstColor));
mock.Verify(mock => mock.Display(secondColor));
Assert.AreNotEqual(firstColor, secondColor);
like image 565
Archer Avatar asked Oct 24 '25 04:10

Archer


1 Answers

It is needed to collect all passed parameters into List<string> colours variable to be able to verify them then.

[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);
}
like image 199
Ilya Palkin Avatar answered Oct 26 '25 22:10

Ilya Palkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!