Search Results for

    Show / Hide Table of Contents

    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

    1. When this attribute is not specified, tests run in the MTA by default.
    2. When running tests in parallel, tests are scheduled to execute on a thread with the specified apartment state.
    3. When parallel execution is disabled, a new thread may be created if the current thread doesn't have the correct apartment state.
    4. This attribute replaces the obsolete RequiresMTA and RequiresSTA attributes.
    5. The ApartmentState.Unknown value is not allowed and will cause an error.

    See Also

    • RequiresThread Attribute
    • SingleThreaded Attribute
    • Parallelizable Attribute
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0