[WPF] 在单元测试中使用 Prism 的 EventAggregator,订阅到 ThreadOption.UIThread 会报错
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 在 PubSubEvent 的 Subscribe 函数中抛出:
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 的话可以参考 PrismApplicationBase 和 PrismInitializationExtensions 写一个初始化类,大概差不多这样(简化了部分代码):
[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 会报错的更多相关文章
- 【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 ...
- webRTC中回声消除(AEC)模块编译时aec_rdft.c文件报错:
webRTC中回声消除(AEC)模块编译时aec_rdft.c文件报错. 原因是: 局部变量ip跟全局变量冲突的问题,可以将局部变量重新命名一下,就可以通过编译了. aec_rdft.c修改以后文件代 ...
- VS项目中使用Nuget还原包后编译生产还一直报错?
Nuget官网下载Nuget项目包的命令地址:https://www.nuget.org/packages 今天就遇到一个比较奇葩的问题,折腾了很久终于搞定了: 问题是这样的:我的解决方案原本是好好的 ...
- 在android 中开发java.net.SocketException: socket failed: EACCES (Permission denied) 报错
在android中下载文件,写好下载文件的代码后需要配置相应的权限 <uses-permission android:name="android.permission.INTERNET ...
- MySQL中查询时"Lost connection to MySQL server during query"报错的解决方案
一.问题描述: mysql数据库查询时,遇到下面的报错信息: 二.原因分析: dw_user 表数据量比较大,直接查询速度慢,容易"卡死",导致数据库自动连接超时.... 三.解决 ...
- hive中创建子表并插入数据过程初始化MR报错解决方法
本文继成上一篇通过hive分析nginx日志文章,详情参考下面链接: http://www.cnblogs.com/wcwen1990/p/7066230.html 接着来: 创建业务子表: drop ...
- webstorm中sass编译时目录或内容包含中文字符报错
ruby版本:ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32] sass版本:Sass 3.4.22 (Selective Steve) ...
- react-native 中使用redux 优化 Connect 使用装饰器简化代码报错
报错信息 error: bundling failed: Error: The 'decorators' plugin requires a 'decoratorsBeforeExport' opti ...
- gazebo仿真踩坑--rviz中设定机器人的目标位置,move_base后台日志报错
启动仿真环境及各种节点(amcl,move_base,map_server)后,在rviz中设定机器人的目标位置,后台日志报错 [ INFO] [1571974242.864525935, 40.51 ...
随机推荐
- Jmeter之分布式执行测试 (2)
一. 安装Java 1.1下载JDK 1) Windows安装jdk,下载完成后,双击安装 2) Linux解压:tar -zxvf jdk-8u74-linux-x64.gz 1.2 Java环境变 ...
- 面试 02-CSS盒模型及BFC
02-CSS盒模型及BFC #题目:谈一谈你对CSS盒模型的认识 专业的面试,一定会问 CSS 盒模型.对于这个题目,我们要回答一下几个方面: (1)基本概念:content.padding.marg ...
- css进阶 05-CSS的一些小知识
05-CSS的一些小知识 #隐藏盒子的几种方式 隐藏盒子,有以下几种方式: (1)方式一: overflow:hidden; //隐藏盒子超出的部分 (2)方式二: display: none; ...
- MySQL高可用(二)主备延时如何解决?
从上篇文章我们知道主备同步是依赖于 binlog,主库负责生产 binlog,备库负责消费 binlog,从而实现主备同步. 今天我们来学习一下主备同步里的一个重点的问题:主备延时. 主备延时,简单来 ...
- 正方形和球体,利用蒙特卡洛计算pi值
clc; clear all; close all; R = 3; time = 10000; origin = [0,0,0]; %%======绘制球体====== t=linspace(0,pi ...
- 教你如何修改Python的pip源镜像
PS:在pip install安装扩展库的时候,遇到安装超时失败,可能是因为国外镜像被屏蔽了. 可以使用国内开放的pip源: 阿里云 http://mirrors.aliyun.com/pypi/si ...
- python3全局函数解析
python的全局函数: import builtins dir(builtins) [ 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray ...
- idea run dashbord使用
idea 中使用dashbord可以迅速开启多个服务方便进行本地测试 开启步骤 1. 打开idea菜单 view-> toolWindows ->service 选项 2. 打开底部的se ...
- 云服务器部署LAMP
一.安装Apache 1.安装httpd服务: sudo yum install httpd 2.开启服务: sudo systemctl start httpd 3.访问服务器IP成功显示Testi ...
- java中io流实现文件上传下载
新建io.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" page ...