【问题标题】:Exception on test of event aggregator subscriptions using Moq使用 Moq 测试事件聚合器订阅的例外情况
【发布时间】:2016-04-22 17:25:23
【问题描述】:

使用以下代码订阅获取 IEnumerable 集合数据时出现不支持的异常。无法订阅已发布的 Collection 对象。

Mock<IEventAggregator> _mockEventAgg = new Mock<IEventAggregator>();
_mockEventAgg.Setup(x => x.GetEvent<ShowScreenEvent>().Publish(new ObservableCollection<Customer>()
              { 
                 // Customer properties or details     
              }));


_mockEventAgg.Setup(m => m.GetEvent<ShowScreenEvent>().Subscribe(It.IsAny<Action<IEnumerable<Customer>>>()))
             .Callback<IEnumerable<Customer>>(customers => SelectedCustomerData = customers);

例外:

Moq.dll 中出现“System.NotSupportedException”类型的异常,但未在用户代码中处理

附加信息:非虚拟(在 VB 中可覆盖)成员的无效设置:m => m.GetEvent().Subscribe(It.IsAny())

【问题讨论】:

  • 从读取异常信息来看,ShowScreenEvent.Subscribe()是非虚拟的吗?
  • ShowScreenEvent 类继承自 PubSubEvent&lt;IEnumerable&lt;Customer&gt;&gt;
  • 看看这个问题stackoverflow.com/questions/35868184/…(你肯定可以将它从 NSubstitute 转换为 Moq)

标签: c# unit-testing moq prism eventaggregator


【解决方案1】:

您需要在设置中添加一个参数,以便模拟正确的订阅方法。 在 prism 中,只有一个带有有效负载的 ent 的订阅方法被标记为虚拟

它看起来像这样

Eventaggregator.Setup(c => c.GetEvent<YourEvent>()
                             .Subscribe(It.IsAny<Action<string>>(),
                                        It.IsAny<ThreadOption>(), 
                                        It.IsAny<bool>(),
                                        It.IsAny<Predicate<string>>()))
                .Returns(YourHandleFunc);

【讨论】:

    【解决方案2】:

    您收到的异常是 Moq 无法设置方法,因为它是非虚拟的。 Moq 不支持对未标记为virtual 的具体类型的模拟方法; see here 了解更多信息。

    在您的情况下,您正在尝试模拟 ShowScreenEvent.Subscribe(...),您说它是在其基类 PubSubEvent&lt;IEnumerable&lt;Customer&gt;&gt; 上定义的。事实上,它是非虚拟的:

    public SubscriptionToken Subscribe(Action<TPayload> action)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      相关资源
      最近更新 更多