views:

138

answers:

3

I have a unit test that tests if an Exception is throw, but this Exception is only throw in Debug mode (via the [Conditional("DEBUG")] Attribute). If I run this test in Release mode, it fails. I tried to apply the same Attribute on the test but it's no taken into account.

How can I exclude a test in Release mode? Does it even make sense to run unit tests in Release mode or should I stick to Debug mode?

+4  A: 

Try this:

#if DEBUG

// here is your test

#endif
Stefan Steinegger
This works but I think it's a too drastic solution. Instead, I used the [Ignore] Attribute (still, it's enclosed inside a #if !DEBUG ... #endif, but I like it better).
Julien Poulin
+2  A: 

If you're using NUnit, you can make your unit test methods conditional:

[System.Diagnostics.Conditional("DEBUG")]
public void UnitTestMethod()
{
   // Tests here
}

This way it will only be executed in DEBUG builds. I don't have a lot of experience with Visual Studio unit tests, but I'm pretty sure that this should work there in VS too.

EDIT: Others have mentionned conditional compilation directives. I don't think that it is a very good idea, for a number of reasons. To learn more about the differences between conditional compilation directives and the conditional attribute, read Eric Lippert's excellent article here.

DrJokepu
I'm using MSTest and it looks like the Conditional Attribute is not honored by the test engine...
Julien Poulin
+2  A: 

As for most of your question, it depends somewhat on what unit testing tool your using. However, in general what you want are preprocessor directives

//C#
#ifndef DEBUG
    //Unit test
#end if

Perhaps for your situation

//C# - for NUnit
#if !DEBUG
    [Ignore("Only valid for release")] 
#end if

But as to whether to leave unit tests in the release version? I'd give a resounding NO. I'd suggest moving all your unit tests into it's own project and NOT including this in your releases.

C. Ross
Of course, all my unit tests are in another project, but I can still run them in Release mode...
Julien Poulin
Why would you really want them to be different in release and debug?
C. Ross
I want to be sure that me code will behave the same in Debug and in Release mode. But in this particular case, I *know* that the test will fail in Release mode since the Exception should only be thrown in Debug mode (by design)
Julien Poulin
Well, I came up with a possible solution, provided your using NUnit.
C. Ross
I ended up using your solution after all. Since I'm using MSTest, the Attribute is [Ignore] (no parameter).
Julien Poulin