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. |
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));
}
}
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
SetUporTearDownmethods. - The Timeout Attribute uses
Thread.Abortand only works on .NET Framework.