NUnit
async methods
unit testing
C# testing
test frameworks

How do I test an async method with NUnit or possibly with another framework?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Async methods should be tested with async tests all the way through. Blocking on .Result or .Wait() changes the execution model, can hide bugs, and makes exception behavior harder to reason about. The clean pattern in NUnit and similar frameworks is to return Task, await the method under test, and use async-aware assertion helpers.

Use async Task Tests

In NUnit, the normal pattern is to make the test method itself asynchronous:

csharp
1using NUnit.Framework;
2using System;
3using System.Threading.Tasks;
4
5public class MathService
6{
7    public async Task<int> DivideAsync(int a, int b)
8    {
9        await Task.Delay(10);
10        if (b == 0) throw new DivideByZeroException();
11        return a / b;
12    }
13}
14
15[TestFixture]
16public class MathServiceTests
17{
18    [Test]
19    public async Task DivideAsync_ReturnsExpectedValue()
20    {
21        var svc = new MathService();
22        var result = await svc.DivideAsync(10, 2);
23        Assert.That(result, Is.EqualTo(5));
24    }
25}

This keeps the test aligned with the real production calling pattern and makes failures easier to interpret.

Assert Async Exceptions Properly

Use async-aware assertion helpers instead of manual try and catch blocks:

csharp
1[Test]
2public void DivideAsync_ThrowsOnZero()
3{
4    var svc = new MathService();
5
6    Assert.ThrowsAsync<DivideByZeroException>(async () =>
7    {
8        await svc.DivideAsync(5, 0);
9    });
10}

That expresses the intent clearly and avoids boilerplate that can hide the actual failure path.

Test Cancellation and Failure Paths

Async code often involves cancellation or async collaborators. Those paths deserve explicit tests, not just a happy-path assertion.

csharp
1using System.Threading;
2using System.Threading.Tasks;
3
4public class Worker
5{
6    public async Task RunAsync(CancellationToken token)
7    {
8        await Task.Delay(3000, token);
9    }
10}
11
12[Test]
13public void RunAsync_HonorsCancellation()
14{
15    var worker = new Worker();
16    using var cts = new CancellationTokenSource();
17    cts.Cancel();
18
19    Assert.ThrowsAsync<TaskCanceledException>(async () =>
20    {
21        await worker.RunAsync(cts.Token);
22    });
23}

If your code maps cancellations or dependency failures into domain-specific errors, test that mapping directly.

Avoid Timing-Based Tests

A common anti-pattern is to start async work, sleep for a fixed delay, and then assert that some side effect happened. Those tests become flaky as soon as machine speed or scheduler load changes.

Prefer one of these:

  • await the actual task
  • control completion with TaskCompletionSource
  • mock async collaborators explicitly

Example:

csharp
1using System.Threading.Tasks;
2
3public interface INotifier
4{
5    Task NotifyAsync(string message);
6}
7
8public class Workflow
9{
10    private readonly INotifier _notifier;
11
12    public Workflow(INotifier notifier)
13    {
14        _notifier = notifier;
15    }
16
17    public async Task ExecuteAsync()
18    {
19        await _notifier.NotifyAsync("done");
20    }
21}

In the test, await ExecuteAsync() and then assert against the mock. That is deterministic and much less fragile than sleeping.

The Same Rules Apply Across Frameworks

xUnit and MSTest use different APIs, but the async testing principles stay the same:

  • return Task
  • await the method under test
  • use framework helpers for async exceptions
  • avoid blocking and arbitrary sleeps

The framework syntax changes. Good async test design does not.

Common Pitfalls

The biggest mistake is using .Result or .Wait() in tests. That can hide real async behavior and sometimes introduce deadlocks.

Another issue is writing async void tests. They lose the normal task-based completion and exception semantics you want in a test.

People also forget to await the method under test, which means assertions may run before the real work finishes.

Summary

  • Write async tests as async Task methods and await the code under test.
  • Use async-aware assertion helpers for exception cases.
  • Test cancellation and failure paths, not just success cases.
  • Avoid blocking calls and sleep-based timing guesses.
  • Apply the same async testing discipline in NUnit, xUnit, and MSTest.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions