chaliasos
chaliasos

Reputation: 9783

Finally block is executed only on Debug mode

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?

Upvotes: 0

Views: 252

Answers (3)

waterbear
waterbear

Reputation: 69

Timeout is disabled during debugging, so you get to see Console.WriteLine() output.

But i still think finally is executed in vs2010. If you try to show a message box System.Windows.Forms.MessageBox.Show("finally") you should be able to see it pops up.

Console.WriteLine output is lost after timeout in vs2010.

Upvotes: 1

Keysharpener
Keysharpener

Reputation: 504

The Timeout attribute simply does not apply to Debugging sessions.

Upvotes: 1

Honza Brestan
Honza Brestan

Reputation: 10947

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 Sleep call and doesn't have time to reach finally block. Debugging probably disables the timeout attribute.

Upvotes: 4

Related Questions