单元测试WPF绑定

Not*_*Dan 10 data-binding wpf binding unit-testing

我正在尝试使用Microsoft Team System提供的测试套件对我的WPF数据绑定进行单元测试.我希望能够在不显示窗口的情况下测试绑定,因为我的大多数测试都是针对用户控件而不是实际上是在窗口上.这可能还是有更好的方法吗?如果我显示窗口,下面的代码可以工作,但如果我没有,则绑定不会更新.

            Window1_Accessor target = new Window1_Accessor();
            UnitTestingWPF.Window1_Accessor.Person p = new UnitTestingWPF.Window1_Accessor.Person() { FirstName = "Shane" };
            Window1 window = (target.Target as Window1);
            window.DataContext = p;         
            //window.Show(); //Only Works when I actually show the window
            //Is it possible to manually update the binding here, maybe?  Is there a better way?
            Assert.AreEqual("Shane", target.textBoxFirstName.Text);  //Fails if I don't Show() the window because the bindings aren't updated
Run Code Online (Sandbox Code Playgroud)

Ben*_*hon 6

在寻找将WPF绑定错误转换为异常的解决方案时,我发现它也可以用于单元测试项目中.

该技术非常简单:

  1. 导出TraceListener抛出而不是记录
  2. 添加该侦听器 PresentationTraceSources.DataBindingSource

请参阅GitHub上完整解决方案,它包括一个单元测试项目.

在Visual Studio中测试失败


Bob*_*ing 2

Shane,如果您真正担心的是绑定无声地中断,您应该考虑将绑定跟踪重定向到您可以检查的地方。我从这里开始:

http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx

除此之外,我同意 Gishu 的观点,即绑定不是单元测试的良好候选者,主要是由于 Gishu 在“结语”中提到的自动魔法。相反,应专注于确保底层类的行为正确。

另请注意,您可以使用PresentationTraceSources 类获得更可靠的跟踪:

http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.aspx

希望有帮助!