【发布时间】:2016-03-21 21:00:49
【问题描述】:
我想通过事件聚合向模块抛出消息来对模块进行单元测试,以确保它适当地响应,或者通过适当地设置属性,或者通过发布其他消息作为结果。我正在使用棱镜 6。 在我的项目中,基础设施项目有:
public class ImportantMessage : PubSubEvent<string>
{
}
ModuleA 发布这样的消息:
eventAggregator.GetEvent<ImportantMessage>().Publish(importantString);
ModuleB 收到这样的消息:
eventAggregator.GetEvent<ImportantMessage>().Subscribe(HandleImportantMessage);
这里是 HandleImportantMessage:
public void HandleImportantMessage(string importantString)
{
. . .
}
ModuleB 构造函数调用如下:
ModuleB(IEventAggregator EventAggregator)
此构造函数由 Prism 框架调用。对于单元测试,我需要创建一个 ModuleB 实例,并传递一个 IEventAggregator,它可能是 Moq 创建的一个假的。我想以这样一种方式做到这一点,即我发布的消息带有importantString。 如果我在 Google 上搜索“带有最小起订量和事件聚合的单元测试”这个短语,有 几个参考,但我没有看到如何使用这些方法中的任何一种将“importantString”从 ModuleA 传递到 ModuleB。 Prism 5 的示例代码创建了一个假事件聚合器,但没有使用 Moq。我不明白它是如何工作的,也不知道如何用它传递一个字符串。
我的测试代码是这样开始的:
var moqEventAggregator = new Mock(IEventAggregator);
var moqImportantMessage = new Mock<ImportantMessage>();
moqEventAggregator.Setup(x => x.GetEvent<ImportantMessage>());
我看到的一些参考文献适用于 .Returns(eventBeingListenedTo.Object); 应用安装程序后到 moqEventAggregator。 我显然需要将 .Setup(something) 应用于 moqImportantMessage 以传递重要字符串,但我还没有看到具体是什么。
我错过了什么?如何传递带有虚假发布消息的字符串?
【问题讨论】:
-
不完全是重复的,但您可能可以将其从 NSubstitute 转移到 Moq:stackoverflow.com/questions/35868184/…
标签: unit-testing moq prism prism-6