Apartment
ApartmentAttribute is used to specify that tests should run in a particular COM apartment state, either STA (Single-Threaded Apartment) or MTA (Multi-Threaded Apartment).
This is primarily needed for tests that interact with COM objects, Windows Forms controls, or WPF components that require a specific apartment state.
Constructor
ApartmentAttribute(ApartmentState apartmentState)
| Parameter | Type | Description |
|---|---|---|
apartmentState |
ApartmentState |
The apartment state for the test. Must be STA or MTA (not Unknown). |
ApartmentState Values
| Value | Description |
|---|---|
ApartmentState.STA |
Single-Threaded Apartment. Required for most UI components (WinForms, WPF, COM controls). |
ApartmentState.MTA |
Multi-Threaded Apartment. The default for NUnit tests. |
Applies To
| Test Methods | Test Fixtures (Classes) | Assembly |
|---|---|---|
| ✅ | ✅ | ✅ |
When applied at multiple levels, the most specific level takes precedence.
Examples
Assembly Level
// All tests in this assembly will use the STA by default
[assembly: Apartment(ApartmentState.STA)]
Test Fixture Level
[TestFixture]
[Apartment(ApartmentState.STA)]
public class WinFormsTests
{
[Test]
public void TestRunsInSTA()
{
// All tests in this fixture run in the STA
Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA));
}
}
Test Method Level
[TestFixture]
public class MixedApartmentTests
{
[Test]
[Apartment(ApartmentState.STA)]
public void TestRequiringSTA()
{
Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA));
}
[Test]
[Apartment(ApartmentState.MTA)]
public void TestRequiringMTA()
{
Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA));
}
}
Notes
- When this attribute is not specified, tests run in the MTA by default.
- When running tests in parallel, tests are scheduled to execute on a thread with the specified apartment state.
- When parallel execution is disabled, a new thread may be created if the current thread doesn't have the correct apartment state.
- This attribute replaces the obsolete
RequiresMTAandRequiresSTAattributes. - The
ApartmentState.Unknownvalue is not allowed and will cause an error.