Tests That Depend on Other Tests
Most tests should be independent: each one sets up what it needs and can run on its own, in any order. Sometimes, though, tests really do depend on each other. An integration test may need an order to exist before it can ship it, or a cleanup step must run after the tests that use a shared resource.
NUnit 5 lets you say this directly with [DependsOnTest] and
[DependsOnFixture].
Note
Test dependencies were added in NUnit 5.0.
Depending on another test
Put [DependsOnTest] on a test, with the name of the test it depends on. Use nameof, so the dependency still works
when the test is renamed.
public class OrderWorkflowTests
{
private static readonly List<string> Orders = [];
[Test]
public void CreateOrder()
{
Orders.Add("order-1");
Assert.That(Orders, Has.Count.EqualTo(1));
}
[Test]
[DependsOnTest(nameof(CreateOrder))]
public void ShipOrder()
{
// Runs only after CreateOrder has passed. If CreateOrder fails, this test is skipped.
Assert.That(Orders, Does.Contain("order-1"));
}
[Test]
[DependsOnTest(nameof(ShipOrder), AllowFailure = true)]
public void CleanUpOrders()
{
// Runs after ShipOrder even if it failed, so the cleanup always happens.
Orders.Clear();
Assert.That(Orders, Is.Empty);
}
}
ShipOrderruns only afterCreateOrderhas finished. IfCreateOrderfails,ShipOrderis skipped instead of failing with a confusing error.CleanUpOrderssetsAllowFailure = true, so it runs even ifShipOrderfailed. This is the pattern for cleanup that must always happen.
Depending on another fixture
When a whole class of tests depends on another class, put [DependsOnFixture] on
the class, with the type of the fixture it depends on. It works the same way: the dependent fixture waits for the other
fixture, and is skipped if that fixture fails, unless AllowFailure is set.
Things to keep in mind
- Tests in a dependency chain can't run in parallel with each other. Don't mark them
[Parallelizable]. - Don't combine dependencies with
[Order]in the same chain.[DependsOnTest]and[DependsOnFixture]replace[Order]for most uses, and[Order]is deprecated. - A circular dependency, or another invalid setup, marks the affected tests as failed, with a message that explains the problem.
See the DependsOnTest and DependsOnFixture reference pages for all the details.