Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to tell in code if we are running from a testmethod .net test

Tags:

c#

.net

testing

Is there a way to know when code is being called from running a test method?

bool MyMethod()
{
    if ( /* are we running a test? */ )
    {
        return true; // otherwise this will fail from the automated build script
    }
    else
    {
        // run the proper code
    } 
}

and please spare me the "this is a really bad idea" comments :)

like image 330
fearofawhackplanet Avatar asked Mar 15 '10 11:03

fearofawhackplanet


2 Answers

You recognize this may be a bad idea, but you may not be aware of the alternatives. You should look into mocking frameworks - they can provide a way to inject alternative implementations into your code at runtime in your unit tests. This is an established practice to allow code to behave differently in test and production.

On to the main question.

This depends on the unit test framework you are using. I'm not aware of a specific feature in NUnit (for example) that reports you are in a test. Other frameworks (like MS Test) may very well provide this. However, it's easy to do yourself.

If you're binding to source code, just use a #define directive to conditionally define some variable you can branch on.

If you're binding to a library, I would recommend creating your own class that you use to track whether you are in a unit test or real code, and set that class up in the TestFixture setup method to indicate you are running a test. You could also use the Environment.SetEnvironmentVariable as a way of avoiding writing a special class.

like image 52
LBushkin Avatar answered Oct 14 '22 08:10

LBushkin


Ok, I'll spare you my "this is a really bad idea" comment.

You can just give the method a parameter bool isTestMode.

like image 41
Klaus Byskov Pedersen Avatar answered Oct 14 '22 07:10

Klaus Byskov Pedersen