Search Results for

    Show / Hide Table of Contents

    SingleThreaded

    SingleThreadedAttribute is used on a test fixture to ensure that OneTimeSetUp, OneTimeTearDown, and all child tests run on the same thread. This forces all child tests to be run sequentially on the current thread.

    Usage

    This is a parameterless attribute that can only be applied to test fixture classes.

    [SingleThreaded]
    

    Applies To

    Test Methods Test Fixtures (Classes) Assembly
    ❌ ✅ ❌

    Example

    [TestFixture]
    [SingleThreaded]
    public class DatabaseTests
    {
        private DbConnection? _connection;
    
        [OneTimeSetUp]
        public void OneTimeSetUp()
        {
            // Connection created on this thread
            _connection = new DbConnection();
            _connection.Open();
        }
    
        [Test]
        public void Test1()
        {
            // Guaranteed to run on the same thread as OneTimeSetUp
            _connection!.Execute("SELECT 1");
        }
    
        [Test]
        public void Test2()
        {
            // Also runs on the same thread
            _connection!.Execute("SELECT 2");
        }
    
        [OneTimeTearDown]
        public void OneTimeTearDown()
        {
            // Runs on the same thread, safe to close connection
            _connection?.Close();
        }
    }
    
    // Simple stub classes for the example
    private class DbConnection
    {
        public void Open() { }
        public void Execute(string sql) { }
        public void Close() { }
    }
    

    Notes

    1. When this attribute is applied, any ParallelScope setting on the fixture or its child tests is ignored.
    2. This attribute is inherited by derived test fixture classes.
    3. Use this attribute when your tests share resources that have thread affinity, such as database connections, COM objects, or UI components.
    4. This attribute only affects the fixture it is applied to. Other fixtures in the same assembly can still run in parallel with this fixture (unless assembly-level parallelization is disabled).

    See Also

    • Parallelizable Attribute
    • NonParallelizable Attribute
    • RequiresThread Attribute
    • Apartment 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