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

后端 未结 3 806
慢半拍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条回答
  •  梦毁少年i
    2020-12-31 04:49

    If you mock both the event and the Event Aggregator, and use moq's Callback, you can do it.

    Here's an example:

    Mock mockEventAggregator;
    Mock mockEvent;
    
    mockEventAggregator.Setup(e => e.GetEvent()).Returns(mockEvent.Object);
    
    // Get a copy of the callback so we can "Publish" the data
    Action callback = null;
    
    mockEvent.Setup(
        p =>
        p.Subscribe(
            It.IsAny>(), 
            It.IsAny(), 
            It.IsAny(), 
            It.IsAny>()))
            .Callback, ThreadOption, bool, Predicate>(
            (e, t, b, a) => callback = e);
    
    
    // Do what you need to do to get it to subscribe
    
    // Callback should now contain the callback to your event handler
    // Which will allow you to invoke the callback on the test's thread
    // instead of the UI thread
    callback.Invoke(new MyEventArgs(someObject));
    
    // Assert
    

提交回复
热议问题