Geeks With Blogs
Andy Johns' Blog Andy's twisted brain....

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

Posted on Thursday, August 5, 2004 10:17 PM | Back to top


Comments on this post: how to tell if your code is running under an NUnit test....

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
Doesn't this kinda go against the idea that components should be decoupled largely from any fore-knowledge (design time) of context in which they run?

I think that folks typically people prefer to use config files because they are the tool that supports this kind of design imperative.

Wouldn't it make more sense to have a single class that represents and controls all message output that can write to all of the output targets, and that the output target can be set using a public member whose runtime state is persisted in a config file?

The solution you provide is a pretty cool example of walkig the stack, but it creates a design dependency that doesn't quite smell right to me. Wouldn't the target component need to be bound to nunit-framework.dll in order for this to work?
Left by Scott Bellware on Aug 06, 2004 7:29 AM

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
You make some good points, but I also see a need for this. I don't like changing config files for unit testing. Not only can it create problems with Continuous Integration but it can also be misused easily. The whole application can know that it's in test mode, and thus more code paths can be targeted against it. And if you have multiple config files it introduces potential problems, one dll’s config is flagged “under test” but not another’s, etc. And if you’re also managing multiple config files for multiple environments it can get to be quite a headache. Also, in my case our QA team does not allow any changes to code or config files while testing.

I definitely believe the use of this detection should be limited. For my current project, we're only using it in a custom MessageBox type dialog that is displayed during an error condition. The main drive for this was the fact our continuous integration service, CruiseControl, (aka CCNet) was hanging when the UI displayed a messagebox during unit testing. Because CCNet hung, the test looked successful, however it was not.

As far as having a dependency to NUnit in the target assembly, this is not a problem for me, as I always put my test classes inside my target assemblies. It is far easier to maintain this way, allows for easier testing of internals without reflection, and allows easier unit testing of classes in executables. We also run NUnit tests against some production systems to ensure successful production rollout.

Finally to address your first point that components should be decoupled from any knowledge of the context in which they run.... I think that good TFD dictates you always are aware that the code will run within unit testing, and you have to code for that. Any technique, config files, this function, or something else to block MessageBoxes, or other GUI elements during unit testing indicates your component is aware it’s being run under test conditions; and while this awareness should be limited, it is needed in some cases.
Left by Andy on Aug 06, 2004 10:52 AM

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
I needed to do this detection but have it work even with NUnit-compatible test frameworks (such as MBUnit) so I had to remove the dependency on the NUnit attribute, like this:

Array Attributes = methodBase.GetCustomAttributes(false);
foreach (object obj in Attributes)
{
if (obj.ToString().Contains("TestAttribute"))
return true;
}
Left by Jim Beveridge on May 06, 2005 12:07 PM

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
This won't always work because test methods do not necessarily have the TestAttribute set. They are also recognized as test methods if they case-insensitively start with "test", and in this case the above methods will fail.
Left by Felix Wiemann on Nov 03, 2005 6:23 AM

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
[SetUpFixture]
public class NUnitDetector
{
private static bool nunitRunning = false;
public bool NUnitRunning { get { return nunitRunning; } }

[SetUp] public void S() { nunitRunning=true; } }
[TearDown] public void T() { nunitRunning=false; } }
}
Left by Rueschi on Aug 08, 2008 2:47 AM

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
Oh, i forgot:

public STATIC bool nunitRunning ...
Left by Rueschi on Aug 08, 2008 2:50 AM

# re: how to tell if your code is running under an NUnit test....
Requesting Gravatar...
Rueschi -
You code is fine for small cases, but it requires the tested code to have a reference to the test assembly, and it assumes one test fixture will be the only test fixture that will test the code. Often in a large project you may have dozens of test assemblies, with hundreds of test fixtures, and some code will be called from many tests....
Left by Andy on Aug 08, 2008 8:23 AM

Your comment:
 (will show your gravatar)


Copyright © Andy Johns | Powered by: GeeksWithBlogs.net