Moq - mock.Raise应该在没有安装程序的情况下在测试单元中引发事件

时间:2011-05-16 11:42:49

标签: c# tdd moq

我有一个演示者类,它附加了一个注入视图的事件。 现在我想测试演示者对事件的正确反应。

这是视图界面IView:

public interface IView 
{
    event EventHandler MyEvent;
    void UpdateView(string test);
}

这是实现IView的视图

public partial class MyView : IView
{
    public event EventHandler MyEvent;

    public MyView()
    {
        this.combo.SelectedIndexChanged += this.OnSelectedIndexChanged;
    }

    public void UpdateView(string test)
    {
        this.textBox.Text = test;
    }

    private OnSelectedIndexChanged(Object sender, EventArgs e)
    {
        if (this.MyEvent != null)
        {
            this.MyEvent(sender, e);
        }
    }
}

这是受测试的主持人:

public class MyPresenter
{
    private IView _view;
    public MyPresenter(IView view)
    {
        this._view = view;
        this._view.MyEvent += this.OnMyEvent;
    }

    private void OnMyEvent(Object sender, EventArgs e)
    {
        this._view.UpdateView();
    }
}

这是测试MyPresenter的测试夹具:

[TestClass]
public class MyPresenterFixture()
{
    private MyPresenter testee;
    private Mock<IView> mockView;

    [TestMethod]
    public void ShouldReactOnMyEvent()
    {
        // arrange
        this.mockView = new Mock<IView>(MockBehavior.Strict);
        this.testee = new MyPresenter(this.mockView.Object);

        // act
        this.mockView.Raise(mock => mock.MyEvent += null); // this does not fire

        // assert and verify
        this.mockView.Verify(mock => mock.UpdateView(It.IsAny<string>());
    }
}

我正在使用Moq 4.我可以做我想做的事吗?

祝你好运 Yannik

2 个答案:

答案 0 :(得分:60)

你不需要传递参数吗?您的事件签名是EvenHandler,即 (object sender, EventArgs e)

this.mockView.Raise(mock => mock.MyEvent += null, new EventArgs());

我从未使用过你在这里指定的重载......但这似乎不正确。

答案 1 :(得分:3)

您已将UpdateView()声明为接受字符串,但您的演示者调用没有字符串参数(或默认值):

调用:

private void OnMyEvent(Object sender, EventArgs e)
{
    this._view.UpdateView();
}

声明:

public void UpdateView(string test)
{
    this.textBox.Text = test;
}

验证

mockView.Verify(mock => mock.UpdateView(It.IsAny<string>());

FWIW,我认为你认为这个事件有点麻烦,一个简单的改变就是:

public interface IView
{
    void UpdateText(string test);
}

public class MyPresenter
{
    private readonly IView _view;
    public MyPresenter(IView view)
    {
        _view = view;
    }

    private void SelectItem(string item)
    {
        _view.UpdateText(item);
    }
}

public partial class MyView : IView
{
    private readonly MyPresenter _presenter;

    public MyView()
    {
        _presenter = new MyPresenter(this);
        combo.SelectedIndexChanged += OnSelectedIndexChanged;
    }

    public void UpdateText(string test)
    {
        textBox.Text = test;
    }

    private OnSelectedIndexChanged(Object sender, EventArgs e)
    {
        _presenter.SelectItem(combo.SelectedItem);
    }
}

然后您可以验证与视图的交互,而无需处理其他事件:

    presenter.SelectItem("Burrito!");

    mockView.Verify(mock => mock.UpdateView("Burrito!");