【发布时间】:2012-02-17 22:10:48
【问题描述】:
我正在尝试遵循 Using the WPF Dispatcher in unit tests 的建议,以运行我的 nUnit 测试。
当我如下编写单元测试时,它可以工作:
[Test]
public void Data_Should_Contain_Items()
{
DispatcherFrame frame = new DispatcherFrame();
PropertyChangedEventHandler waitForModelHandler = delegate(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Data")
{
frame.Continue = false;
}
};
_myViewModel.PropertyChanged += waitForModelHandler;
Dispatcher.PushFrame(frame);
Assert.IsTrue(_myViewModel.Data.Count > 0, "Data item counts do not match");
}
但是,如果我尝试使用 DispatcherUtil 的建议,它不起作用:
[Test]
public void Data_Should_Contain_Items()
{
DispatcherUtil.DoEvents();
Assert.IsTrue(_myViewModel.Data.Count > 0, "Data item counts do not match");
}
public static class DispatcherUtil
{
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
private static object ExitFrame(object frame)
{
((DispatcherFrame)frame).Continue = false;
return null;
}
}
当我使用 DispatcherUtil 时,看起来对 ExitFrame 的调用发生得太快了,数据还没有准备好。
我没有正确使用 DispatcherUtil 吗?这似乎是一种更好的方法来处理调度程序,而不是等待来自视图模型的回调。
【问题讨论】:
-
如果 PropertyChangedEventHandler 为属性“数据”调用,您要测试什么?如果是这样,为什么需要调度员参与?我也没有使用 _myViewModel 来附加处理程序。
-
@Phil:当 _myViewModel 被实例化时,它的构造函数会进行异步调用。当该调用完成时,_myViewModel.Data 应该有一些值。我正在尝试测试 Data 实际上是否已填充,但是由于 asyn 调用而填充 Data 的事实给我带来了一些麻烦。我想避免在可能必须处理 Dispatcher 的任何单元测试中监听 PropertyChanged 事件。
标签: c# wpf unit-testing nunit dispatcher