Verifying event registration using Moq

后端 未结 4 1909
悲&欢浪女
悲&欢浪女 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 16:37

    I spent some time with this question and the solution which I'm using in my project is:

    Unit test:

    // Arrange
    TestedObject.Setup(x => x.OnEvent1());
    TestedObject.Setup(x => x.OnEvent2());
    
    // Act
    TestedObject.Object.SubscribeEvents();
    TestedObject.Raise(x => x.Event1 += null);
    TestedObject.Raise(x => x.Event2 += null);
    
    // Assert
    TestedObject.Verify(x => x.OnEvent1(), Times.Once());
    TestedObject.Verify(x => x.OnEvent2(), Times.Once());
    

    Tested method:

    this.Event1 += OnEvent1;
    this.Event2 += OnEvent2;
    

    So, first you have to mock the methods which you will assign the events, after you call the method which you want to test, and finally raise all subscribed events. If the event is really subscribed, you can check with Moq if the assigned method is called.

    GLHF!

提交回复
热议问题