最小起订量 - 模拟.提高应在没有设置的情况下在测试单元中引发事件



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

这是视图界面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>());
    }
}

我正在使用最小起订量 4。可以做我想做的事吗?

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

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

我从未使用过您在此处指定的重载...不过,这似乎不正确。

您已将 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!");

相关内容

  • 没有找到相关文章

最新更新