Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSTest - unit test with StackOverflowException

Tags:

c#

mstest

I wrote program in C# that invokes MSTest from command line. One of test cases throws StackOverflowException and it causes, that QtAgent32 (and my application) process breaks. What can I do to prevent from this situation (I can't change unit tests)?

like image 507
mirt Avatar asked Nov 11 '10 16:11

mirt


People also ask

Can we handle StackOverflowException?

NET Framework 2.0, you can't catch a StackOverflowException object with a try / catch block, and the corresponding process is terminated by default. Consequently, you should write your code to detect and prevent a stack overflow.

What causes StackOverflowException?

A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }

Should unit tests be run in debug or release?

I'd recommend running the release code. For a couple of reasons. 1) It is the code that the customers will be using. 2) Some code has special debug conditionals that will produce differences between the debug and release builds.


2 Answers

One way by which you can avoid these kind of crashes is by setting the legacyUnhandledExceptionPolicy property in QTAgent32.exe.config (and/or QTAgent.exe.config depending upon the bitness of the machine/testrun) as mentioned here. Relevant text from this link is: -

As a temporary compatibility measure, administrators can place a compatibility flag in the section of the application configuration file. This causes the common language runtime to revert to the behavior of versions 1.0 and 1.1.

This will switch the "unhandled exception" handling behaviour to .net 1.1 and the process will not crash on such exceptions.

like image 131
Aseem Bansal Avatar answered Oct 07 '22 17:10

Aseem Bansal


The problem is that you cannot catch StackOverflowException on .NET (starting with the 2.0 version). This probably means that there is no way to solve the problem you have - because the unit testing framework simply cannot catch the exception.

See the following related SO question:

  • C# catch a stack overflow exception.

There are some interesting suggestions on the other thread - for example, you can create Thread and check the current FrameCount to detect the stack overflow earlier. However, that probably won't be very reliable. So, I'm afraid there is no good answer...

like image 31
Tomas Petricek Avatar answered Oct 07 '22 17:10

Tomas Petricek