验证是否通过Moq调用了代表
问题描述:
我有一个类,该类通过参数获得一个委托. 此类调用该委托,我想用Moq对它进行单元测试. 我如何验证此方法是否被调用?
i got a class that gets by argument a delegate. This class invokes that delegate, and i want to unit test it with Moq. how do i verify that this method was called ?
示例类:
public delegate void Foo(int number);
public class A
{
int a = 5;
public A(Foo myFoo)
{
myFoo(a);
}
}
,我想检查是否调用了Foo. 谢谢.
and I want to check that Foo was called. Thank you.
答
使用匿名函数怎么办?它可以像内联模拟一样,您不需要模拟框架.
What about using an anonymous function? It can act like an inline mock here, you don't need a mocking framework.
bool isDelegateCalled = false;
var a = new A(a => { isDelegateCalled = true});
//do something
Assert.True(isDelegateCalled);