Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

NUnit STA Threads & Testing WPF

0.00/5 (No votes)
17 Jun 2009 1  
NUnit STA threads and testing WPF

During the course of the WPF project we are working on at work, we decided to go down the Agile/XP/TDD/Mocks/Continuous Integration route, which means Unit tests, lots of them.

We are using NUnit, which I really like, but we are also using WPF, we are obviously using the latest/greatest patterns AKA MVVM, but from time to time, it is nice to be able to test certain things on WPF controls/windows, etc.

So I set out to create a small NUnit test like the following:

37323/diag11.jpg

Now to me this looked fine, but when I ran this code, I got the following horror show.

37323/stathread-thumb.jpg

Where NUnit moaned about “The calling thread must be STA”. Oh, that’s to bad. So I had a small think, and then came up with this small idea, just pass the original code to a helper class and have it run that in a Thread using STA threading apartment state. Sounds cool, but did it work. Well yes actually it did, and here is the small helper class.

37323/diag2.jpg

And here is how to use this from a NUnit test.

37323/diag3.jpg

And just to prove it works, here is a screen shot of the actual test running successfully.

37323/stathreadok-thumb.jpg

Here is a link to a small test project that you can see this working with in case you want to use this in your own projects.

Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here