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
- When this attribute is applied, any
ParallelScopesetting on the fixture or its child tests is ignored. - This attribute is inherited by derived test fixture classes.
- Use this attribute when your tests share resources that have thread affinity, such as database connections, COM objects, or UI components.
- 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).