Verifying event registration using Moq

后端 未结 4 1889
悲&欢浪女
悲&欢浪女 2020-12-15 16:08

I\'m developing an asp.net (classic) application trying to implement the MVP pattern using this example. In trying to unit test my presenter and using the following pattern,

4条回答
  •  囚心锁ツ
    2020-12-15 17:01

    I know it's maybe too late for #Dilip, but this answer can be helpful for those who are trying to do the same. Here is the test class

    public delegate void SubscriptionHandler(string name, T handler);
    
    public class SomePresenterTest
    {
        [Test]
        public void Subscription_Test()
        {
            var someServiceMock = new Mock();
            var viewMock = new Mock();
            //Setup your viewMock here
    
            var someView = new FakeView(viewMock.Object);
            EventHandler initHandler = null;            
            someView.Subscription += (n, h) => { if ((nameof(someView.Init)).Equals(n)) initHandler=h; };
    
            Assert.IsNull(initHandler);
    
            var presenter = new SomePresenter(someServiceMock.Object, someView);
    
            Assert.IsNotNull(initHandler);
            Assert.AreEqual("OnInit", initHandler.Method?.Name);
        }
    }
    

    FakeView is a decorator implemented as follow (pay attention to Events:Init/Load{add;remove}):

    public class FakeView : IView
    {
        public event SubscriptionHandler Subscription;
        public event SubscriptionHandler Unsubscription;
        private IView _view;
        public FakeView(IView view)
        {
            Assert.IsNotNull(view);
            _view = view;
        }
    
        public bool IsPostBack => _view.IsPostBack;
        public bool IsValid => _view.IsValid;
    
        public event EventHandler Init
        {
            add
            {
                Subscription?.Invoke(nameof(Init), value);
                _view.Init += value;
            }
    
            remove
            {
                Unsubscription?.Invoke(nameof(Init), value);
                _view.Init -= value;
            }
        }
        public event EventHandler Load
        {
    
            add
            {
                Subscription?.Invoke(nameof(Load), value);
                _view.Init += value;
            }
    
            remove
            {
                Unsubscription?.Invoke(nameof(Load), value);
                _view.Init -= value;
            }
        }
    
        public void DataBind()
        {
            _view.DataBind();
        }
    }
    

提交回复
热议问题