Testing WPF controls in NUnit
Tagged as WPFYou can instantiate and test WPF controls in a NUnit test in the usual way:
MyTestControl control = new MyTestControl(); Assert.AreEqual(someValue, control.MyProperty);
This will appear to work wonderfully until you run it as part of your automated build, at which point it will fail on the first line, complaining that UIElements have to be created in the STA.
This happens because when you’re running the tests, you’re probably using the NUnit GUI or TestDriven.NET, which run their tests on a STA thread, but the build server is probably using the NUnit console, which runs tests on a MTA thread.
You can fix this by creating an app.config file in your test project with the following content:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="NUnit"> <section name="TestRunner" type="System.Configuration.NameValueSectionHandler" /> </sectionGroup> </configSections> <NUnit> <TestRunner> <add key="ApartmentState" value="STA" /> </TestRunner> </NUnit> </configuration>
NUnit will now run all tests in the STA, regardless of GUI or console environment. Your tests can now create UIElements and controls as required.
Leave a Reply
Categories
BrainDump (1)
Community Code (4)
Events (15)
F# (11)
General (50)
Lab Samples (2)
LightSpeed (249)
MegaPack (7)
News (68)
NHibernate Designer (18)
Nightly news (40)
Phone Elements (22)
Products (87)
Projects (5)
Screencast (6)
SharePoint (3)
Silverlight (14)
Silverlight Elements (59)
SimpleDB Management Tools (20)
Visual Studio (9)
VS File Explorer (7)
Web Workbench (20)
WPF (43)
WPF Diagrams (53)
WPF Elements (91)
WPF Property Grid (32)



Posted by Ivan Towlson on 25 March 2008 


