简体   繁体   English

使用Moq验证是否调用了任一方法

[英]Use Moq to Verify if either method was called

I am trying to write a test that verifies that either Foo or FooAsync were called. 我正在尝试编写一个测试来验证是否调用了FooFooAsync 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? 是否可以通过Verify来执行此操作?

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();
    }
}

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();
        }
    }
}

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? 是否有一个moq的扩展方法可以为我做这个? Or is there anyway to get the method invocation count? 或者无论如何都要获取方法调用计数?

You can create setups for the methods and add callbacks for them, then use that to set a boolean to test. 您可以为方法创建设置并为它们添加回调,然后使用它来设置要测试的布尔值。

eg something like: 例如:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM