Sometimes you need to know if your code is running within a NUnit test or not. For example, you don't want to pop-up a MessageBox if you're running under test during an automated build process....
Some developers use a boolean that gets passed around, and some use specific application config properties, and some create odd workarounds to isolate pop-up boxes, and some simply don't unit-test their GUIs....
I prefer to use custom messagebox that first detects if the code is running under NUnit, and if so, directs what normally would be a message to the user to a log file.
Here's a basic function that will detect if the code is running within a NUnit test:
public static bool IsRunningUnderNUnit()
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
for(int i=0;i<trace.FrameCount;i++)
{
System.Reflection.MethodBase methodBase = trace.GetFrame(i).GetMethod();
if(methodBase.IsDefined(typeof(NUnit.Framework.TestAttribute), true))
{
return true;
}
}
return false;
}
How it works:
Basically it just crawls back through the stack trace looking to see if any methods had a [Test] attribute. If so, you're running under a test, if not you're not.
Hope it helps....
-Andy