[英]Use Moq to Verify if either method was called
我正在尝试编写一个测试来验证是否调用了Foo
或FooAsync
。 我不关心哪一个,但我需要确保至少有一个方法被调用。
是否可以通过Verify
来执行此操作?
所以我有:
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();
}
}
如果我尝试写一个测试:
[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();
}
}
}
我可以尝试捕获断言异常,但这似乎是一个非常奇怪的工作。 是否有一个moq的扩展方法可以为我做这个? 或者无论如何都要获取方法调用计数?
您可以为方法创建设置并为它们添加回调,然后使用它来设置要测试的布尔值。
例如:
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.