如果基于条件执行了方法,请使用xUnit和Moq进行验证

时间:2018-04-05 12:34:44

标签: c# .net-core moq xunit.net

使用xUnit和Moq检查是否根据另一个方法的返回值执行方法。例如:

[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(), """all exactly time that M1 returned false"""); // if this were possible it would be perfect
}

我想验证这样的事情:

material-community

是否可以使用xUnit和Moq?

执行类似的操作

1 个答案:

答案 0 :(得分:5)

你应该可以这样做:

    [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");
    }