Wednesday, January 09, 2008

Nunit and STAThread story

I use NUnit unit-testing framework to test my pet project Twebst. Being a collection of COM objects, Twebst can be used within any environment that supports COM. That means it can be used from .Net languages like C#.

First I started by creating an assembly to be used from NUnit GUI. Some tests failed without an obvious reason. After some research I understood that the COM apartment must be STAThread. The threading model must be set before the thread is started but I don't have access to NUnit GUI main thread from my assembly.

One possible solution to this problem is to transform the assembly into an EXE application that uses the NUnit framework like this:

public static void Main(string[] args)
new string[] { System.AppDomain.CurrentDomain.BaseDirectory + "MyExe.exe", "/nothread" });
When /nothread command line flag is used the tests are executed by the main thread which already has the right COM apartment properly set.


Anonymous said...


There is also a nice solution to this problem posted at (I have tried it and it works for me).

An application configuration file (app.config) must be added to your VS project containing the following data:

<?xml version="1.0" encoding="utf-8"?>

<sectionGroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>

<add key="ApartmentState" value="STA" />


This will force NUnit to use STA threading model.

Unknown said...

Thank you for sharing the solution!

Anonymous said...

Yes, thanks, the solution works well.

Alex K

Unknown said...

You are welcome

Anonymous said...

hi there! I am new to the board and just wanted to introduce myself :)

Unknown said...

Hi there and welcome aboard