【发布时间】:2011-01-27 21:27:02
【问题描述】:
我正在使用 Prism/Composite 应用程序库并尝试对使用 EventAggregator 订阅 CompositePresentationEvent 的一些代码进行单元测试。引发事件的代码在另一个线程上引发它,所以我使用 ThreadOption.UIThread 订阅事件。
当事件引发回调时,它使用应用程序调度程序将其放到 UI 线程上。这在正常执行期间很好,但在单元测试期间没有调度程序。 CompositePresentationEvent 中的代码如下所示:
private IDispatcherFacade UIDispatcher
{
get
{
if (uiDispatcher == null)
{
this.uiDispatcher = new DefaultDispatcher();
}
return uiDispatcher;
}
}
public class DefaultDispatcher : IDispatcherFacade
{
/// <summary>
/// Forwards the BeginInvoke to the current application's <see cref="Dispatcher"/>.
/// </summary>
/// <param name="method">Method to be invoked.</param>
/// <param name="arg">Arguments to pass to the invoked method.</param>
public void BeginInvoke(Delegate method, object arg)
{
if (Application.Current != null)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method, arg);
}
}
}
问题在于 CompositePresentationEvent 与 DefaultDispatcher 相关联,如果没有应用程序运行,此调度程序将不执行任何操作。
有没有人在这种情况下进行过成功的单元测试?有什么技巧或解决方法可以让调度员活跃起来吗?
我知道我可以将回调设为内部并允许我的单元测试调用此方法,但我不希望更改我的代码并将此方法作为最后的手段。
【问题讨论】:
-
如果您尝试对您的课程进行单元测试(不是
CompositePresentationEvent),那么在您的测试中引入真正的CompositePresentationEvent实例会使它们成为非单元。也许你应该将你的类与它隔离,然后使用模拟/存根而不是玩 CPE? -
是的,公平点。我想当我应该能够模拟它们时,我对这些课程提出的问题感到有些困惑。我会尝试安德森的建议,看看它是否能解决它。谢谢!
标签: .net unit-testing prism dispatcher