1. 问题

[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
ContainerLocator.Container.Resolve<TestViewModel>();
}
} public class TestViewModel
{
public TestViewModel(IEventAggregator eventAggregator)
{
var testEvent = eventAggregator.GetEvent<TestEvent>();
testEvent.Subscribe(() => { }, ThreadOption.UIThread);
}
} public class TestEvent : PubSubEvent
{ }

上面是一段使用了 Prism 的单元测试,它主要的逻辑是在 EventAggregator 中订阅了 TestEvent,当接收到消息后在 UI 线程上执行后续的逻辑。这种代码在正常程序中没有问题,但在单元测试中会报错:

System.InvalidOperationException: To use the UIThread option for subscribing, the EventAggregator must be constructed on the UI thread.

2. 原因

翻翻源码,可以发现这个 Exception 在 PubSubEventSubscribe 函数中抛出:

switch (threadOption)
{
case ThreadOption.PublisherThread:
subscription = new EventSubscription(actionReference);
break;
case ThreadOption.BackgroundThread:
subscription = new BackgroundEventSubscription(actionReference);
break;
case ThreadOption.UIThread:
if (SynchronizationContext == null) throw new InvalidOperationException(Resources.EventAggregatorNotConstructedOnUIThread);
subscription = new DispatcherEventSubscription(actionReference, SynchronizationContext);
break;
default:
subscription = new EventSubscription(actionReference);
break;

SynchronizationContext 为 null 时就会判断当前不在 UI 线程,然后抛出 Exception。而 SynchronizationContext 又是在 EventAggregator 中赋值:

private readonly SynchronizationContext syncContext = SynchronizationContext.Current;

public TEventType GetEvent<TEventType>() where TEventType : EventBase, new()
{
lock (events)
{
EventBase existingEvent = null; if (!events.TryGetValue(typeof(TEventType), out existingEvent))
{
TEventType newEvent = new TEventType();
newEvent.SynchronizationContext = syncContext;
events[typeof(TEventType)] = newEvent; return newEvent;
}
else
{
return (TEventType)existingEvent;
}
}
}

问题就出在 SynchronizationContext.Current 这里。这个属性用于获取当前线程的同步上下文。不是每一个线程都有一个 SynchronizationContext 对象。一个总是有 SynchronizationContext 对象的是UI线程。由于单元测试并不是运行在 UI 线程,所以这个属性在单元测试中一直为 null。

3. 解决方案

现在我们知道问题原因了,解决方案也很简单,只要自定义一个 EventAggregator,源码全部照抄,但是把这句:

private readonly SynchronizationContext syncContext = SynchronizationContext.Current;

替换成这句:

private readonly SynchronizationContext syncContext = new SynchronizationContext();

就不会出现 PubSubEvent 中 SynchronizationContext 等于 null 的情况了。然后再把这个类注册到容器中作为 IEventAggregator:

ContainerLocator.Current.RegisterSingleton<IEventAggregator, MyEventAggregator>();

4. 最后

根据单元测试项目的结构,容器的初始化会有不同的方式,如果想尽量模仿 PrismApplication 的话可以参考 PrismApplicationBasePrismInitializationExtensions 写一个初始化类,大概差不多这样(简化了部分代码):

[TestClass]
public abstract class TestInitializerBase
{
public void Initialize()
{
ContainerLocator.SetContainerExtension(() => new UnityContainerExtension());
ContainerExtension = ContainerLocator.Current; ContainerExtension.RegisterSingleton<IDialogService, DialogService>();
ContainerExtension.RegisterSingleton<IModuleInitializer, ModuleInitializer>();
ContainerExtension.RegisterSingleton<IModuleManager, ModuleManager>();
ContainerExtension.RegisterSingleton<RegionAdapterMappings>();
ContainerExtension.RegisterSingleton<IRegionManager, RegionManager>();
ContainerExtension.RegisterSingleton<IRegionNavigationContentLoader, RegionNavigationContentLoader>(); ContainerExtension.RegisterSingleton<IEventAggregator, EventAggregator>(); ContainerExtension.RegisterSingleton<IRegionViewRegistry, RegionViewRegistry>();
ContainerExtension.RegisterSingleton<IRegionBehaviorFactory, RegionBehaviorFactory>();
ContainerExtension.Register<IRegionNavigationJournalEntry, RegionNavigationJournalEntry>();
ContainerExtension.Register<IRegionNavigationJournal, RegionNavigationJournal>();
ContainerExtension.Register<IRegionNavigationService, RegionNavigationService>(); RegisterRequiredTypes(ContainerExtension); } public IContainerExtension ContainerExtension { get; private set; } protected abstract void RegisterRequiredTypes(IContainerRegistry containerRegistry);
} public class TestInitializer : TestInitializerBase
{
[AssemblyInitialize]
public static void InitializeAseemble(TestContext testContext)
{
var testInitializer = new TestInitializer();
testInitializer.Initialize();
} protected override void RegisterRequiredTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IEventAggregator, MyEventAggregator>();
}
}

这样在 TestInitializer 中可以注册各种方便单元测试的伪对象。

[WPF] 在单元测试中使用 Prism 的 EventAggregator,订阅到 ThreadOption.UIThread 会报错的更多相关文章

  1. 【docker】【redis】2.docker上设置redis集群---Redis Cluster部署【集群服务】【解决在docker中redis启动后,状态为Restarting,日志报错:Configured to not listen anywhere, exiting.问题】【Waiting for the cluster to join...问题】

    参考地址:https://www.cnblogs.com/zhoujinyi/p/6477133.html https://www.cnblogs.com/cxbhakim/p/9151720.htm ...

  2. webRTC中回声消除(AEC)模块编译时aec_rdft.c文件报错:

    webRTC中回声消除(AEC)模块编译时aec_rdft.c文件报错. 原因是: 局部变量ip跟全局变量冲突的问题,可以将局部变量重新命名一下,就可以通过编译了. aec_rdft.c修改以后文件代 ...

  3. VS项目中使用Nuget还原包后编译生产还一直报错?

    Nuget官网下载Nuget项目包的命令地址:https://www.nuget.org/packages 今天就遇到一个比较奇葩的问题,折腾了很久终于搞定了: 问题是这样的:我的解决方案原本是好好的 ...

  4. 在android 中开发java.net.SocketException: socket failed: EACCES (Permission denied) 报错

    在android中下载文件,写好下载文件的代码后需要配置相应的权限 <uses-permission android:name="android.permission.INTERNET ...

  5. MySQL中查询时"Lost connection to MySQL server during query"报错的解决方案

    一.问题描述: mysql数据库查询时,遇到下面的报错信息: 二.原因分析: dw_user 表数据量比较大,直接查询速度慢,容易"卡死",导致数据库自动连接超时.... 三.解决 ...

  6. hive中创建子表并插入数据过程初始化MR报错解决方法

    本文继成上一篇通过hive分析nginx日志文章,详情参考下面链接: http://www.cnblogs.com/wcwen1990/p/7066230.html 接着来: 创建业务子表: drop ...

  7. webstorm中sass编译时目录或内容包含中文字符报错

    ruby版本:ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32] sass版本:Sass 3.4.22 (Selective Steve) ...

  8. react-native 中使用redux 优化 Connect 使用装饰器简化代码报错

    报错信息 error: bundling failed: Error: The 'decorators' plugin requires a 'decoratorsBeforeExport' opti ...

  9. gazebo仿真踩坑--rviz中设定机器人的目标位置,move_base后台日志报错

    启动仿真环境及各种节点(amcl,move_base,map_server)后,在rviz中设定机器人的目标位置,后台日志报错 [ INFO] [1571974242.864525935, 40.51 ...

随机推荐

  1. Kubernetes【K8S】(一):Kubernetes组件

    什么是Kubernetes ​ Kubernetes 是一个可移植的.可扩展的开源平台,用于管理容器化的工作负载和服务,可促进声明式配置和自动化.Kubernetes拥有一个庞大且快速增长的生态系统. ...

  2. wsgi和asgi的关系

    什么是WSGI #CGI CGI(Common Gateway Interface,通用网关接口),定义客户端与Web服务器的交流方式的一个程序,例如正常情况下客户端发送过来一个请求,根据HTTP协议 ...

  3. 网络编程-python实现-TCP实现文件下载(1.1.4)

    @ 目录 代码实现 代码实现 客户端 from socket import * def main(): # 创建socket tcp_client_socket = socket(AF_INET, S ...

  4. python绘制美丽花朵

    from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import Line ...

  5. CODING DevOps 线下沙龙回顾二:SDK 测试最佳实践

    讲师:潘志刚 声网质量效能部门负责人,超过 14 年服务器.移动终端.音视频编解码以及汽车电子等跨行业从业经历,负责建立测试基础架构和自动化测试方案,主持搭建持续集成测试生态体系.现任声网质量效能部门 ...

  6. C# Attribute特性 泛型<T> 方法的out ref this(扩展方法) Equals与==

    out ref out和ref的使用场景其实不一样.out适合在方法内返回一个额外的结果参数,而ref适合直接改变一个在方法外面的值,方法改变外部就改变,无需重新定义接住返回值再使用. out可以在方 ...

  7. Java进阶专题(二十) 消息中间件架构体系(2)-- RabbitMQ研究

    前言 接上文,这个继续介绍RabbitMQ,并理解其底层原理. 介绍 RabbitMQ是由erlang语言开发,基于AMQP(Advanced Message Queue 高级消息队列协议)协议实现的 ...

  8. Centos7安装packstack

    Centos7安装packstack 步骤一 下载centos7.6 https://archive.kernel.org/centos-vault/7.6.1810/isos/x86_64/Cent ...

  9. android 使用 Lottie

    1.添加依赖 dependencies { implementation 'com.airbnb.android:lottie:2.5.5'//lottie } 2.1layout实现 <?xm ...

  10. spring mvc与mybatis事务整合

    之前公司用的是mybatis,但事务管理这块是用ejb的CMT容器管理的事务.基本原理是ejb请求进来,业务代码会创建一个mybatis的session然后放入当前线程,之后所有的方法操作涉及到数据库 ...