简体   繁体   中英

How can I make a unit test run in DEBUG mode only?

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?

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
#endif

Perhaps for your situation

//C# - for NUnit
#if !DEBUG
    [Ignore("This test runs only in debug")] 
#endif 

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.

Try this:

#if DEBUG

// here is your test

#endif

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 .

Similar solution for NUnit framework(only debugging test works):

public class DebugOnlyAttribute : NUnitAttribute, IApplyToTest
{

    private const string _reason = "Debug only";

    public void ApplyToTest(Test test)
    {
        if (!Debugger.IsAttached)
        {
            test.RunState = RunState.Ignored;
            test.Properties.Set(PropertyNames.SkipReason, _reason);
        }

    }
}

[DebugOnly]
[Test]
public void TestMethod()
{ 
//your test code
}

If you're using XUnit, you can use the following method as described by Jimmy Bogard by extending the fact attribute:

public class RunnableInDebugOnlyAttribute : FactAttribute
{
    public RunnableInDebugOnlyAttribute()
    {
        if (!Debugger.IsAttached)
        {
            Skip = "Only running in interactive mode.";
        }
    }
}

and then you can use this as follows:

[RunnableInDebugOnly]
public void Test_RunOnlyWhenDebugging()
{
    //your test code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM