Dilshod K
Dilshod K

Reputation: 3032

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?

Upvotes: 2

Views: 1405

Answers (2)

Dilshod K
Dilshod K

Reputation: 3032

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

Upvotes: 0

Charlie
Charlie

Reputation: 13736

The reason the NUnit framework itself doesn't have a way to set a default timeout is that this is considered the job of the program used to run the tests.

If you are running the tests in your pipeline using the NUnit Console runner, the argument --timeout:XXXX may be used to set the default timeout in milliseconds.

If you are using vstest to run the tests, you need to add an entry to your .runsettings file. The entry for default timeout is DefaultTimeout.

Upvotes: 3

Related Questions