我正在尝试编写一个测试来验证是否调用了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();
}
}
}
我可以尝试捕获断言异常,但这似乎是一个非常奇怪的解决方法。 有没有一种扩展方法可以为我做到这一点? 还是无论如何都可以获取方法调用计数?
您可以为方法创建设置并为其添加回调,然后使用它来设置要测试的布尔值。
例如:
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);