Unit Testing View Binding

Apr 27, 2011 at 2:52 PM

Since I am in a small dev environment I do not have a UI tester.  I really like WPF binding except when something isn't setup right you have to remember to check in snoop or something to know that there is a binding error.

I have already created unit tests that check that the button on the left menu panel loads the proper view into my content control. 

I want to test a view that would normally be loaded into the content control.  I would like it to pass the view a model that has all the values filled and then check each textbox (or label etc) and make sure that it has the value that I put into the model.  If something didn't bind right I would assume the value would be blank for that box or all the boxes depending on the binding error.

I have something like this started:

try
{
    Bxf.Shell.Instance.ShowView(
    typeof(TestDotNet.Views.TestView).AssemblyQualifiedName,
      "TestViewModelViewSource",
      new TestDotNet.ViewModels.TestViewModel(5),
      "Main");
}
catch (Exception ex)
{
      Assert.Fail(ex.Message);
}

Assert.AreEqual("Main", _region);
Assert.AreEqual("TestDotNet.Views.TestView, TestDotNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", _view.ViewName);
object wantedNode = _view.ViewInstance.FindName("TestNumber");
if (wantedNode is TextBlock)
{
      // Following executed if Text element was found.
     TextBlock wantedChild = wantedNode as TextBlock;
     Assert.AreEqual("Test", wantedChild.Text);
}
else
{
      Assert.Fail("FileNumber TextBlock not found");
}
Unfortunately the _view.ViewInstance is null so the code errors out there.  How do I access the controls on the view?  I am new to MVVM and Unit testing so I am guessing at how to do all of this so any push in the right direction would be great.
Thanks,
Mark
Coordinator
May 4, 2011 at 4:09 PM

I generally try to avoid creating UI elements during the unit test run, because they could have side-effects that cause problems in a non-interactive test scenario.

However, you can certainly go ahead and create the view if you'd like. It is your test shell that is not creating the view - if you followed my example you have a view factory that returns null. Just use the standard view factory, and it will create the view instance as normal.