MaxTime
MaxTimeAttribute is used on test methods to specify a maximum time in milliseconds for a test case. If the test takes longer than the specified time to complete, it is reported as a failure.
Unlike CancelAfter, this attribute does not cancel the test - it waits for the test to complete and then checks the elapsed time.
Constructor
MaxTimeAttribute(int milliseconds)
| Parameter |
Type |
Description |
milliseconds |
int |
The maximum elapsed time in milliseconds. If the test exceeds this time, it fails. |
Named Parameters
| Parameter |
Type |
Description |
WarningTime |
int |
An optional warning threshold in milliseconds. If the test takes longer than this time but less than the maximum time, the test result is set to Warning. A value of 0 (the default) disables the warning threshold. (NUnit 5+) |
Applies To
| Test Methods |
Test Fixtures (Classes) |
Assembly |
| ✅ |
❌ |
❌ |
Examples
Basic Usage
[TestFixture]
public class PerformanceTests
{
[Test]
[MaxTime(1000)]
public void OperationCompletesWithinOneSecond()
{
// This test fails if it takes more than 1000ms
var result = PerformQuickCalculation();
Assert.That(result, Is.Not.Null);
}
[Test]
[MaxTime(5000)]
public async Task AsyncOperationCompletesWithinFiveSeconds()
{
// MaxTime also works with async tests
await Task.Delay(100);
Assert.Pass();
}
private object PerformQuickCalculation()
{
// Simulate a quick calculation
return new object();
}
}
Assertion Failures Take Precedence
[TestFixture]
public class MaxTimeVsAssertionTests
{
[Test]
[MaxTime(2000)]
public void AssertionFailuresTakePrecedence()
{
// If both assertion fails AND time exceeds,
// the assertion failure is reported
var result = 2 + 2;
Assert.That(result, Is.EqualTo(4));
}
}
Warning Threshold
[TestFixture]
public class MaxTimeWarningThresholdTests
{
[Test]
[MaxTime(1000, WarningTime = 200)]
public void OperationWithWarningThreshold()
{
// Test passes if it completes within 1000ms.
// If it takes more than 200ms but less than 1000ms, the result is Warning.
Thread.Sleep(201);
}
}
Notes
- Any assertion failures take precedence over the elapsed time check. If a test both fails an assertion and exceeds the time limit, the assertion failure is reported.
- This attribute does not cancel or abort the test if the time is exceeded. It waits for the test to complete, then compares the elapsed time to the maximum.
- For tests that need to be cancelled when they exceed a time limit, use CancelAfter Attribute instead.
- The timing includes the test method execution only, not
SetUp or TearDown methods.
- The Timeout Attribute uses
Thread.Abort and only works on .NET Framework.
- The optional
WarningTime named parameter (added in NUnit 5+) sets a soft threshold: if the test exceeds it but still passes within the maximum time, the result is Warning rather than Failure.
See Also