Search Results for

    Show / Hide Table of Contents

    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

    1. 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.
    2. 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.
    3. For tests that need to be cancelled when they exceed a time limit, use CancelAfter Attribute instead.
    4. The timing includes the test method execution only, not SetUp or TearDown methods.
    5. The Timeout Attribute uses Thread.Abort and only works on .NET Framework.

    See Also

    • CancelAfter Attribute
    • Timeout Attribute
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0