Testing NUnit on a STA Thread

Recently ran into an issue where ManualResetEvent was used in combination with WaitHandle.WaitAll . This issue was confusing at first, as our test suite ran all tests successfully.

In this particular case, the following exception was thrown: WaitAll for multiple handles on a STA thread is not supported.

Although the description is helpful, it took a bit of time to figure out what was happening and how to reproduce it. It was a while since I developed a Windows Forms application (or a WCF service for that matter) and remembered that some of the project templates automatically add theĀ  STAThread

But how do you test for STAThread in Unit tests? Turns out, it's by adding the following attribute to your test case.

[Apartment(ApartmentState.STA)]

Full example:

/// <summary>
/// Perform connection test using STAThread.
/// </summary>
/// <param name="host">host name</param>
/// <param name="port">port number</param>
/// <param name="username">username</param>
/// <param name="password">password</param>
[Test]
[Apartment(ApartmentState.STA)]
[Category("Connection")]
[TestCase("127.0.0.1", 123, "user", "pass")]
public void ConnectSTA_ConnectionSuccessful_ExpectedPass(string host, int port, string username, string password)
{
	try
	{
		Server server = new Server(host, port, username, password);
		server.Init();
	}
	catch(Exception e)
	{
		Assert.Fail(e.Message);
	}
	
	Assert.Pass();
}


Profile picture
Gideon Bakx
Updated on: Friday, October 6, 2023 8:10:53 PM
C# certified software engineer living in Calgary, Canada.
NUnit C# .NET