单元测试 WPF 绑定 [英] Unit test WPF Bindings
问题描述
我正在尝试使用 Microsoft Team System 提供的测试套件对我的 WPF 数据绑定进行单元测试.我希望能够在不显示窗口的情况下测试绑定,因为我的大多数测试将针对用户控件而不是实际在窗口上.这是可能的还是有更好的方法来做到这一点?如果我显示窗口,下面的代码有效,但如果我不显示,则绑定不会更新.
I am trying to unit test my WPF databindings using the test suit provided by Microsoft Team System. I would like to be able to test the bindings without showing the window because most of my tests will be for user controls and not actually on a window. Is this possible or is there a better way to do it? The code below works if I show the window, but if I don't, the bindings don't update.
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
推荐答案
Shane,如果您真正担心的是绑定无声无息地破坏,您应该考虑将绑定跟踪重定向到您可以检查的地方.我会从这里开始:
Shane, if what you're really worried about is a binding breaking silently, you should look at redirecting the binding traces to somewhere you can examine. I'd start here:
http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx
除此之外,我同意 Gishu 的观点,即绑定不是单元测试的良好候选者,主要是因为 Gishu 在尾声"中提到的自动魔术.而是专注于确保底层类的行为正确.
Other than that, I agree with Gishu that bindings aren't good candidates for unit testing, mainly due to the automagic going on that Gishu mentioned in the "Epilogue". Instead focus on making sure the underlying class behaves correctly.
还要注意,您可以使用 PresentationTraceSources 类获得更可靠的跟踪:
Note, too, that you can get even more robust traces using the PresentationTraceSources class:
http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.aspx
希望有帮助!
这篇关于单元测试 WPF 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!