xUnit
02 / 02

xUnit: Fixtures, Mocking & Parallelism

xUnit: Fixtures, Mocking & Parallelism

Teardown via IDisposable

public class DatabaseTests : IDisposable
{
    private readonly SqlConnection _connection;

    public DatabaseTests()
    {
        _connection = new SqlConnection(TestConnectionString);
    }

    // Called after EACH test -- mirrors the constructor-as-setup
    // pattern, since a fresh instance is disposed after every test
    public void Dispose()
    {
        _connection.Close();
    }
}

IClassFixture<T>: Shared, Expensive Setup

public class DatabaseFixture : IDisposable
{
    public SqlConnection Connection { get; }
    public DatabaseFixture() { Connection = ConnectToTestDb(); }
    public void Dispose() { Connection.Close(); }
}

// Shares ONE DatabaseFixture instance across every test in this class,
// instead of xUnit's default per-test constructor recreating an
// expensive real connection for every single test method
public class OrderRepositoryTests : IClassFixture<DatabaseFixture>
{
    private readonly DatabaseFixture _fixture;
    public OrderRepositoryTests(DatabaseFixture fixture) { _fixture = fixture; }
}

Mocking with Moq

// xUnit handles test structure/assertions; a separate library
// like Moq handles mocking dependencies -- used together
[Fact]
public void GetUser_ReturnsUser()
{
    var mockRepo = new Mock<IUserRepository>();
    mockRepo.Setup(r => r.GetById(1)).Returns(new User { Id = 1 });

    var service = new UserService(mockRepo.Object);

    Assert.NotNull(service.GetUser(1));
}

Traits & Running Tests

[Fact]
[Trait("Category", "Integration")]
public void FullOrderFlow_CompletesSuccessfully() { /* ... */ }
dotnet test                              # run all tests
dotnet test --filter Category!=Integration  # run only fast unit tests

Parallel Execution Caveat

Test CLASSES run in parallel by default (tests within the same class run sequentially). Avoid relying on shared, mutable external state -- like a fixed temp file path or a static field -- that different test classes might read/write simultaneously, which can cause flaky, hard-to-reproduce failures.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free