Moq - mock.Raise should raise event in tested unit without having a Setup

后端 未结 2 2019
傲寒
傲寒 2020-12-29 19:01

I have a presenter class, that attaches an event of the injected view. Now I would like to test the presenter reacting on correctly on the event.

This is the view in

相关标签:
2条回答
  • 2020-12-29 19:33

    Don't you need to pass the argument? Your event signature is EventHandler, which is
    (object sender, EventArgs e).

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

    I've never used the overload you've specified here... it doesn't seem correct, though.

    0 讨论(0)
  • 2020-12-29 19:53

    You've declared UpdateView() as accepting a string, but your presenter invocation does not have a string argument (or default):

    Invocation:

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

    Declaration:

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

    Verification:

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

    FWIW, I think the event in your view is a bit cumbersome, a simple change would be to:

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

    Then you could just verify the interaction with the view without having an additional event to deal with:

        presenter.SelectItem("Burrito!");
    
        mockView.Verify(mock => mock.UpdateView("Burrito!");
    
    0 讨论(0)
提交回复
热议问题