« Dealing with Frustrating Development Issues | Main | NUnit "Quick and Dirty" Tutorial »

May 03, 2006

Dealing with Frustrating Development Issues - Part 2 (The End)

As I previously wrote I was having some issues with trying to get a parent window from MSHTML.IHTMLDocument2. Turns out that the issue is the NUnit GUI!

Who would have thought that a unit testing tool affects how you have to write your core application code, but that seems to be the case. No wonder running these tests worked previously - I was using the NUnit console application. When you use the NUnit GUI, you have to take into account that it uses MTA (multi-threaded apartment threading model) by default. The way I got my code to work was to set the default threading model to STA (single-threaded apartment) like so:

System.Threading.Thread.CurrentThread.ApartmentState = System.Threading.ApartmentState.STA;

The reason this is necessary is because the call to IHTMLDocument2.parentElement has to be done from the main thread. Otherwise you get a nasty System.InvalidCastException. If you're running the NUnit console, it's not a problem because the main thread is the test thread. But if you're running the NUnit GUI, the main thread is the GUI thread so I kept running up against that nasty exception. Setting your code to run in STA mode fixes this problem.

After hours of searching, banging my head against the wall, trying dozens of solutions, it all comes down to a single line of code. I set this in the Browser static constructor so it's automatically executed whenever you use ABCWebTest. I didn't want to force all ABCWebTest.NET users to have to put this line into their NUnit tests.

Posted by Misha Rybalov at May 3, 2006 11:50 AM

Comments

Post a comment




Remember Me?