使用Moq验证Prism事件订阅失败 [英] Using Moq to verify a Prism event subscription fails

查看:92
本文介绍了使用Moq验证Prism事件订阅失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Moq一起使用Prism框架.我正在尝试验证AlarmService订阅了构造函数中的事件,但是我收到一个不支持此事件的异常.

I am using the Prism framework together with Moq. I am trying to verify that the AlarmService subscribes to an event in the constructor but I am getting an exception that this is not supported.

我还能如何验证呢?

这是我的testMethod:

This is my testMethod:

public void TestMethod()
{
    var mockMachineDataService = new Mock<IMachineDataService<AlarmDto>>();
    var mockAggregator = new Mock<IEventAggregator>();
    var mockEvent = new Mock<MachineMessageReceivedEvent>();
    mockAggregator.Setup(x => x.GetEvent<MachineMessageReceivedEvent>()).Returns(mockEvent.Object);

    var alarmService = new AlarmService(mockAggregator.Object, mockMachineDataService.Object);
    Assert.IsNotNull(alarmService);

    mockAggregator.VerifyAll();
    mockEvent.Verify(x => x.Subscribe(It.IsAny<Action<MachineMessage>>(), It.IsAny<ThreadOption>()));
}

运行此程序时,出现以下故障:

When I am running this I get the following failure:

System.NotSupportedException: Invalid verify on a non-virtual (overridable in VB) member: x => x.Subscribe(It.IsAny<Action`1>(), It.IsAny<ThreadOption>())

我确实看过这并拆分了模拟Aggregator和模拟事件以获得上面的代码,但仍然失败.

I did have a look at this and split up the mockAggregator and mockEvent to get the above code, but it still fails.

推荐答案

我猜是问题所在,Subscribe方法已重载,最后调用了另一个具有更多默认选项的Subscribe方法,该方法是虚拟的.通过更改测试以验证此虚拟方法,我可以验证是否已调用了subscription方法.

I guess the problem was that the Subscribe method is overloaded and in the end calls another Subscribe method with more default options which is virtual. By changing the test to verify this virtual method I can verify that the subscribe method has been called.

[TestMethod]
public void TestConstructorSubscribesToMachineMessages()
{
    var mockMachineDataService = new Mock<IMachineDataService<AlarmDto>>();
    var mockAggregator = new Mock<IEventAggregator>();
    var mockEvent = new Mock<MachineMessageReceivedEvent>();
    mockAggregator.Setup(x => x.GetEvent<MachineMessageReceivedEvent>()).Returns(mockEvent.Object);
    mockEvent.Setup(x => x.Subscribe(It.IsAny<Action<MachineMessage>>(), It.IsAny<ThreadOption>(), It.IsAny<bool>(), It.IsAny<Predicate<MachineMessage>>()));

    var alarmService = new AlarmService(mockAggregator.Object, mockMachineDataService.Object);
    Assert.IsNotNull(alarmService);

    mockAggregator.VerifyAll();
    mockEvent.VerifyAll();
}

这篇关于使用Moq验证Prism事件订阅失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆