Use Moq to Verify if either method was called

Phi*_*tle 5 c# unit-testing moq

I am trying to write a test that verifies that either Foo or FooAsync were called. I don't care which one, but I need to make sure at least one of those methods were called.

Is it possible to get Verify to do this?

So I have:

public interface IExample
{
    void Foo();
    Task FooAsync();
}

public class Thing
{
    public Thing(IExample example) 
    {
        if (DateTime.Now.Hours > 5)
           example.Foo();
        else
           example.FooAsync().Wait();
    }
}
Run Code Online (Sandbox Code Playgroud)

If I try to write a test:

[TestFixture]
public class Test
{
    [Test]
    public void VerifyFooOrFooAsyncCalled()
    {
        var mockExample = new Mock<IExample>();

        new Thing(mockExample.Object);

        //use mockExample to verify either Foo() or FooAsync() was called
        //is there a better way to do this then to catch the exception???

        try
        {
            mockExample.Verify(e => e.Foo());
        }
        catch
        {
            mockExample.Verify(e => e.FooAsync();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

I could try and catch the assertion exception, but that seems like a really odd work around. Is there an extension method for moq that would do this for me? Or is there anyway to get the method invocation count?

Owe*_*ing 6

您可以为这些方法创建设置并为它们添加回调,然后使用它来设置要测试的布尔值。

例如:

var mockExample = new Mock<IExample>();

var hasBeenCalled = false;
mockExample.Setup(e => e.Foo()).Callback(() => hasBeenCalled = true);
mockExample.Setup(e => e.FooAsync()).Callback(() => hasBeenCalled = true);

new Thing(mockExample.Object);

Assert.IsTrue(hasBeenCalled);
Run Code Online (Sandbox Code Playgroud)

  • @OwenPauling - 那么就没有办法获得模拟的调用计数了吗? (2认同)