Verify if a method was executed depending on the return value of another method

0

With xUnit and Moq verify if a method is executed depending on the return value of another method. Example:

public class A 
{
    public bool M1() { // return true or false ... }
    public void M2() { // Do something ..... }
}

public class B 
{
    private A objectA;

    public B(A a)
    {
        objectA = a;
    }

    public void Mb ()
    {
        for(int i = 0; i <= 5; i++)
        {
            if (!objectA.M1())
                continue;
            objectA.M2();
       }
    }
}

I want to verify something like this:

[Fact]
public void Test()
{
    // Arrange
    Mock<A> mockA = new Mock<A>();
    mockA.Setup(x => x.M1()).Return(true);
    mockA.Setup(x => x.M2());

    // Act
    B b = new B(mockA.object);
    b.Mb();

    // Assert
    mockA.Verify(m => m.M2(), """si M1 retorno true"""); // esto me resolveria si fuera posible algo como eso
}

Note that if M1 returns TRUE "n" times M2 would be executed exactly "n" times. Is it possible to do this with xUnit and Moq ??

    
asked by Guille 04.04.2018 в 21:53
source

1 answer

0

Someone helped me with the answer I was looking for and it is this:

[Fact]
public void Test()
{
    // Arrange
    Mock<A> mockA = new Mock<A>();
    int count = 0;
    mockA.Setup(x => x.M1()).Returns(true).Callback(() => { count++; });
    mockA.Setup(x => x.M2());

    // Act
    B b = new B(mockA.Object);
    b.Mb();

    // Assert
    mockA.Verify(m => m.M2(), Times.Exactly(count), "all exactly time that M1 returned false");
}
    
answered by 12.04.2018 / 15:11
source