测试订阅EventAggregator

时间:2016-01-18 14:20:52

标签: c# unit-testing testing eventaggregator

感谢SO answer我设法测​​试PRISM EventAggregator的发布事件(伪造FakeItEasy)

[TestCase]
public void test_that_publish_occured()
{
    var fakeEventAg = A.Fake<IEventAggregator>();
    var fakeEvent = A.Fake<MyEvent>();

    A.CallTo(() => fakeEventAg.GetEvent<MyEvent>())
      .Returns(fakeEvent);

    MyViewModel mvm = new MyViewModel(fakeEventAg);

    mvm.ICommandThatCausesPublishToBeCalled.Execute();

    A.CallTo(() => fakeEvent.Publish(A<SomeClass>.Ignored))
      .MustHaveHappened();
}

但是我没有测试订阅此事件。我尝试了以下但是我得到了一个例外&#34;非虚拟方法无法截获&#34;。

[TestCase]
public void test_that_event_is_listened()
{
    var fakeEventAg = A.Fake<IEventAggregator>();
    var fakeEvent = A.Fake<MyEvent>();
    A.CallTo(() => fakeEventAg.GetEvent<MyEvent>())
      .Returns(fakeEvent);

    // subscription occurs in the constructor
    MyViewModel2 mvm2 = new MyViewModel2(fakeEventAg);

    A.CallTo(() => fakeEventAg.GetEvent<MyEvent>()
      .Subscribe(A<Action<PayloadClass>>.Ignored))
      .MustHaveHappened();
}

如何测试是否发生了对事件的订阅?它不必是单元测试,但也可以是集成测试。

1 个答案:

答案 0 :(得分:1)

发生错误是因为Subscribe方法不是虚拟的,因此无法模拟。我看到EventBase类(MyEvent所基于的)具有Subscriptions属性。您应该能够检查该集合以验证您的事件已被添加。