Search code examples
c#testability

Is it ok to use #if debug directive in C#?


We have a class a class that looks something like the following:

public class Processor
{
    //set timeout in seconds
    private const int TIMEOUT = 600;

    public void Process()
    {
        //DO SOMETHING HERE

        //CHECK TO SEE IF TIMEOUT HAS BEEN HIT
    }
}

Essentially, we'd like to write a unit test to see if a timeout is experienced after the specified amount of time. Obviously, we don't want to have to wait 10 minutes each time we run tests. With this in mind, my question is:

How can we manage this value so that it could be, perhaps, 10 seconds during testing but 10 minutes in production? There are many obvious ways to do this, but I'm trying to determine what the cleanest way would be. Should we expose this as a property? Include it as a constructor parameter? Include it as a method parameter? Use compiler directives?


Solution

  • For your exact scenario, I'd probably have a appSettings variable that determines the timeout for the appropriate server (dev/whatever).

    In general though, it is quite appropriate to use the #if DEBUG directive at appropriate times. But in general, you'll only use that when you actually want to prevent compilation of the given code inside it, in release mode.

    A classic reason to use such a directive, at least from when I've found, is to stop logging statements being included at all, in release code. Another is when you may include a certain general library in all projects, but certain code in it is not relevant for a given platform you are deploying to (i.e. Compact Framework doesn't have X class, so you use the directive to determine CF mode, and write code accordingly).