Eyeball it.
Such declarative markup rarely breaks. If someone is not in the manual and does not spin it. Even then you can fix it in a few minutes. IMHO, the cost of writing such tests far exceeds the benefits.
Update [Dec3.08]: Then, fine.
The test simply verifies that the text field is set to "FirstName" as the binding's Path property. If I change / refactor FirstName to JustName in the actual data source object, the test will pass anyway, since it is testing an anonymous type. (The green test when breaking the code is TDD Antipattern: The Liar) If your goal is to verify that FirstName is specified in XAML,
Assert.AreEqual("FirstName", txtBoxToProbe.GetBindingExpression(TextBox.TextProperty).ParentBinding.Path.Path);
If you really have to break broken bindings with unit tests (and don't want to show the user interface), use a real data source ... struggling for a while and came up with this.
[Test] public void TestTextBoxBinding() { MyWindow w = new MyWindow(); TextBox txtBoxToProbe = w.TextBox1; Object obDataSource = w;
Afterword: There real hidden material happens when Window.Show() called. This somehow magically sets the DataItem property, after which the data binding starts working.
// before show bindingExpr.DataItem => null bindingExpr.Status => BindingStatus.Unattached // after show bindingExpr.DataItem => {Actual Data Source} bindingExpr.Status => BindingStatus.Active
Once the binding is active, I think you can force text fields to be updated using this code.
txtBoxToProbe.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
Once again, I express my reluctance against this approach. Getting NUnit to run in the STA was a pain.
Gishu Dec 01 '08 at 17:58 2008-12-01 17:58
source share