Search code examples
c#nunit

Setting default timeout in NUnit tests


Sometimes my pipeline is failing on Azure DevOps because of timeout. It is showing a message like:

Aborting test run: test run timeout of 2700000 milliseconds exceeded

Some tests are taking more than expected, but I don't know which tests they are. So, I know that every test should not take more than 2 minutes and I want to set a timeout. I don't want to add a timeout attribute for each test and require adding a timeout attribute on newly created tests.

I want to set the default timeout for my tests. And after timeout, I want to see the failed test. After some research, I find out that it is not supported: https://github.com/nunit/nunit/issues/1040

I found one solution but it doesn't looks good: I am starting Timer in SetUp and stopping it on TernDown:

System.Timers.Timer timer;
        public System.Timers.Timer Timer
        {
            get
            {
                if (timer == null)
                {
                    timer = new System.Timers.Timer();
                    timer.Interval = 120000;
                    timer.Elapsed += Timer_Elapsed;
                }
                return timer;
            }
        }

        void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Timer.Stop();
            Assert.Fail("Timeout");
        }

        [SetUp]
        public void Setup()
        {
            Timer.Start();
        }

        [TearDown]
        public void TernDown()
        {
            Timer.Stop();
        }

It is working but if the test is taking more than 2 minutes it is not failing immediately.

Does anyone have the same problem and have any solution?


Solution

  • After some research, I found a solution. It seems we can put the Timeout attribute in class also. Since, I need to put it on base class I still have problem because it is not working when I set it to base class. It looks like bug and reported here: https://github.com/nunit/nunit/issues/4156