使用Moq调用方法时如何引发事件? [英] How do I raise an event when a method is called using Moq?

查看:61
本文介绍了使用Moq调用方法时如何引发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的界面:

public interface IMyInterface
{
    event EventHandler<bool> Triggered;
    void Trigger();
}

在单元测试中,我有一个模拟对象,如下所示:

And I've got a mocked object in my unit test like this:

private Mock<IMyInterface> _mockedObject = new Mock<IMyInterface>();

我想做这样的事情:

// pseudo-code
_mockedObject.Setup(i => i.Trigger()).Raise(i => i.Triggered += null, this, true);

但是,在返回的ISetup接口上看起来不像Raise可用.我该怎么做?

However it doesn't look like Raise is available on the ISetup interface that gets returned. How do I do this?

推荐答案

您的伪代码几乎可以找到.您需要使用Raises而不是Raise.在 Moq快速入门:事件中查看Moq 4.x版本,您会看到哪里你弄错了.

Your pseudo-code was almost spot on. You needed to use Raises instead of Raise. Check the Moq Quickstart: Events for versions Moq 4.x and you will see where you made the mistake.

_mockedObject.Setup(i => i.Trigger()).Raises(i => i.Triggered += null, this, true);

这是片段形式GitHub

// Raising an event on the mock
mock.Raise(m => m.FooEvent += null, new FooEventArgs(fooValue));

// Raising an event on a descendant down the hierarchy
mock.Raise(m => m.Child.First.FooEvent += null, new FooEventArgs(fooValue));

// Causing an event to raise automatically when Submit is invoked
mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty);
// The raised event would trigger behavior on the object under test, which 
// you would make assertions about later (how its state changed as a consequence, typically)

// Raising a custom event which does not adhere to the EventHandler pattern
public delegate void MyEventHandler(int i, bool b);
public interface IFoo
{
  event MyEventHandler MyEvent; 
}

var mock = new Mock<IFoo>();
...
// Raise passing the custom arguments expected by the event delegate
mock.Raise(foo => foo.MyEvent += null, 25, true);

这篇关于使用Moq调用方法时如何引发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆