How do I test Prism event aggregator subscriptions, on the UIThread?

后端 未结 3 798
慢半拍i
慢半拍i 2020-12-31 04:07

I have a class, that subscribes to an event via PRISMs event aggregator.

As it is somewhat hard to mock the event aggregator as noted here, I just instantiate a real

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 05:01

    I really think you should use mocks for everything and not the EventAggregator. It's not hard to mock at all... I don't think the linked answer proves much of anything about the testability of the EventAggregator.

    Here's your test. I don't use MSpec, but here's the test in Moq. You didn't provide any code, so I'm basing it on the linked-to code. Your scenario is a little harder than the linked scenario because the other OP just wanted to know how to verify that Subscribe was being called, but you actually want to call the method that was passed in the subscribe... something more difficult, but not very.

    //Arrange!
    Mock eventAggregatorMock = new Mock();
    Mock eventBeingListenedTo = new Mock();
    
    Action theActionPassed = null;
    //When the Subscribe method is called, we are taking the passed in value
    //And saving it to the local variable theActionPassed so we can call it.
    eventBeingListenedTo.Setup(theEvent => theEvent.Subscribe(It.IsAny>()))
                        .Callback>(action => theActionPassed = action);
    
    eventAggregatorMock.Setup(e => e.GetEvent())
                       .Returns(eventBeingListenedTo.Object);
    
    //Initialize the controller to be tested.
    PlantTreeController controllerToTest = new PlantTreeController(eventAggregatorMock.Object);
    
    //Act!
    theActionPassed(3);
    
    //Assert!
    Assert.IsTrue(controllerToTest.MyValue == 3);
    

提交回复
热议问题