|
|||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionWhat is development without unit testing? When developing software using WPF, you will hit a brick wall when creating your first unit test. You will encounter the The Cause of this ProblemThe cause of this problem is that NUnit runs in an MTA while WPF must run in STA. I found the solution to this problem here. I used this class (with some minor changes) in my [Test]
public void TestMainWindow()
{
AvalonTestRunner.RunInSTA(
delegate
{
MainWindow window = new MainWindow();
Assert.AreEqual(300, window.Height);
});
}
More Than Just an AssertWPF is a very cool, flexible and powerful platform... I just felt like saying it:) Basically, you can use Unit Testing DataBindingWhen you say "WPF", the first thing that comes to mind is the DataBinding feature. I guess DataBinding is one of the strongest features in WPF. Yet when you have an error "OOPS" nothing happens and nothing works. The reason why this happens is that WPF catches the exception for us and logs the error in the Trace (silent, but deadly). In actual fact, when there is a binding error, you can see the error in the Visual Studio debug window which is the default trace listener. It would be great if there was a way in which you can unit test databinding, wouldn't it? So I decided to dig into this and have a look at what one can do. I found a very good article on WPF tracing over here. This article shed some light on what is happening and how I can create a small class that can unit test databinding for me. I said, why don't I create a trace listener that can assert whenever a WPF databinding exception is raised. Basically this solution can make your XAML databinding testable! So I created a class that listens to these databinding warnings and asserts to show me that there is a problem in the XAML. Basically the class ( public override void WriteLine(string message)
{
if (currentWindowBeingTested != null)
currentWindowBeingTested.Close();
Assert.Fail(message);
}
So the code to test a Window or a control for data binding would look something like this: [Test]
public void TestDataBindingForControls()
{
AvalonTestRunner.RunInSTA(delegate
{
AvalonTestRunner.RunDataBindingTests(new MainWindow());
AvalonTestRunner.RunDataBindingTests(new UserControlTests());
});
}
The process of testing the Window/control is very simple. You pass an instance of the object that contains your XAML and the It is very important that your control is not using resources from the public Window1() : this(false)
{}
public Window1(bool unitTesting)
{
if(unitTesting)
Resources.MergedDictionaries.Add(new BrushesResources());
InitializeComponent();
}
Then pass the instance for the unit test passing It is very important that you merge the Download the library and have loads of WPF fun. History
|
||||||||||||||||||||||||||||||||||||||||||||