简体   繁体   English

验证是否通过Moq调用了代表

[英]Verifying a delegate was called with 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. 此类调用该委托,我想用Moq对它进行单元测试。 how do i verify that this method was called ? 我如何验证此方法被调用?

example class : 示例类:

public delegate void Foo(int number);

public class A
{
   int a = 5;

   public A(Foo myFoo)
   {
      myFoo(a);
   }
}

and I want to check that Foo was called. 我想检查一下Foo是否被呼叫。 Thank you. 谢谢。

As of this commit Moq now supports the mocking of delegates, for your situation you would do it like so: 从此提交起, Moq现在支持代理的模拟,对于您的情况,您可以这样做:

var fooMock = new Mock<Foo>();
var a = new A(fooMock.Object);

Then you can verify the delegate was invoked: 然后,您可以验证委托是否已被调用:

fooMock.Verify(f => f(5), Times.Once);

Or: 要么:

fooMock.Verify(f => f(It.IsAny<int>()), Times.Once);

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

Moq does not support mocking delegates. Moq不支持模拟委托。 But you can create some interface, with method, which matches your delegate signature: 但是,您可以使用一些方法来创建与您的委托签名相匹配的接口:

public interface IBar
{
    void M(int number);
}

Then create mock, which implements this interface, and use this mock object to create delegate: 然后创建实现此接口的模拟程序,并使用此模拟对象创建委托:

Mock<IBar> bar = new Mock<IBar>();
Foo foo = new Foo(bar.Object.M); 
A a = new A(foo);
bar.Verify(x => x.M(5));   

After exercising your sut, you will be able to verify expectations on your mocked object. 练习后,您将可以验证对模拟对象的期望。

UPDATE: Actually you can simply pass bar.Object.M to your sut, without Foo delegate instance creation. 更新:实际上,您可以简单地将bar.Object.M传递给sut,而无需创建Foo委托实例。 But anyway, mocking delegates requires interface creation. 但是无论如何,模拟委托都需要创建接口。

You can do something like that: 您可以执行以下操作:

 public interface IWithFOOMethod
 {
     void FooAlikeMethod(int number);
 }

 Mock<IWithFOOMethod> myMock = new Mock<IWithFOOMethod>();

 A a = new A(myMock.Object.FooAlikeMethod);

 myMock.Verify(call => call.Foo(It.IsAny<int>()), Times.Once())

Since Moq doesn't support mocking delegates, I'll usually handle this with something like: 由于Moq不支持模拟委托,因此我通常将通过以下方式处理:

var list = new List<int> ();
var del = i => list.Add (i);
var a = new A(del);
list.ShouldContainOnly (new[] { 5 });

where the delegate provided performs some simple, verifiable action. 提供的代表执行了一些简单的可验证的操作。

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

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