[英]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.