Documentation

Documentation
V5 Documentation

NCrunch-Specific Overrides

Often when troubleshooting problems with NCrunch, it can be useful to introduce behavioural differences in your code or build process that are applicable only to NCrunch.

For example, you may have a custom build step performing an action that NCrunch shouldn't take, or a particular piece of test code that needs to be compiled slightly differently under NCrunch.

There are several ways of introducing conditional behaviour under NCrunch.

Conditional Build Behaviour

When executing any kind of build, NCrunch will always inject a special property that can be used to identify it during the build. The property is $(NCrunch) with a value of 1.

This property can be applied to standard build conditions within project files and build imports, for example:

<OutputPath Condition="'$(NCrunch)' == '1'">bin\</OutputPath>
<OutputPath Condition="'$(NCrunch)' != '1'">bin\Debug\</OutputPath>

The above conditional OutputPath properties will introduce different build behaviour for NCrunch. All NCrunch builds will place build outputs directly into the bin directory, while normal builds will output to bin\Debug.

Because MSBuild conditions can be applied just about anywhere inside the build process, this is a very powerful way to introduce any kind of alternative build behaviour for NCrunch.

A possible alternative is to inject your own properties into MSBuild using NCrunch configuration.

Conditional Compilation

In C#, NCrunch builds declare a specialised compiler constant that makes conditional compilation very simple. The declared constant is NCRUNCH. Consider the following example:

#if NCRUNCH
    Console.WriteLine("Running under NCrunch");
#else
    Console.WriteLine("Running under something else");
#endif

When building and executing the above code, the text written to the console will be different between NCrunch and any other test runner.

Conditional Runtime Behaviour

Although conditional compilation is usually a cleaner approach to conditional runtime behaviour, it isn't available for every .NET language and may not be appealing in every situation.

NCrunch always sets an environment variable in its execution environment, which can be queried to identify when NCrunch is resident. This environment variable is under the name NCrunch and is always set to 1. For example:

if (Environment.GetEnvironmentVariable("NCrunch") == "1")
{
    Console.WriteLine("Running under NCrunch");
}
else
{
    Console.WriteLine("Running under something else");
}

An alternative approach is to rely on the NCrunchEnvironment Class, which has a method that tests this environment variable itself:

if (NCrunch.Framework.NCrunchEnvironment.NCrunchIsResident())
{
    Console.WriteLine("Running under NCrunch");
}
else
{
    Console.WriteLine("Running under something else");
}
Trial NCrunch
Take NCrunch for a spin
Do your fingers a favour and supercharge your testing workflow
Free Download