Question is taken from here: SO – Timeout in c# tests
I created a simple unit test like this:
[Timeout(1000)][TestMethod]
public void TestMethod1()
{
try
{
System.Threading.Thread.Sleep(2000);
}
finally
{
Console.WriteLine("Executed");
}
}
When I run the test, the finally block is not executed. But when I debug it, it does. Why is this happening?
You specify the test timeout at 1000 ms, while your method sleeps for 2000 ms. This results in your test method being prematurely force-closed by the test framework, so it doesn’t leave the
Sleepcall and doesn’t have time to reachfinallyblock. Debugging probably disables the timeout attribute.