如何才能在DEBUG模式下运行单元测试?

时间:2009-10-30 11:22:25

标签: .net unit-testing debugging

我有一个单元测试,用于测试是否抛出异常,但是此异常仅在调试模式下抛出(通过[条件(“DEBUG”)]属性)。如果我在发布模式下运行此测试,则会失败。我尝试在测试中应用相同的属性,但没有考虑到它。

如何在发布模式下排除测试?在Release模式下运行单元测试甚至是否应该坚持调试模式是否有意义?

5 个答案:

答案 0 :(得分:13)

至于你的大多数问题,它在某种程度上取决于你使用的单元测试工具。但是,一般来说,你想要的是preprocessor directives

//C#
#ifndef DEBUG
    //Unit test
#endif

也许适合你的情况

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

但是关于是否在发布版本中保留单元测试?我会给出一个响亮的NO。我建议将所有单元测试移到它自己的项目中,而不是在你的发行版中包含它。

答案 1 :(得分:6)

试试这个:

#if DEBUG

// here is your test

#endif

答案 2 :(得分:5)

如果您正在使用NUnit,则可以使您的单元测试方法成为条件:

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

这样它只会在DEBUG版本中执行。我没有很多Visual Studio单元测试的经验,但我很确定这也适用于VS.

编辑:其他人提到了条件编译指令。出于多种原因,我认为这不是一个好主意。要了解有关条件编译指令与条件属性之间差异的更多信息,请阅读Eric Lippert's excellent article here

答案 3 :(得分:1)

NUnit框架的类似解决方案(仅调试测试有效):

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
}

答案 4 :(得分:0)

如果您正在使用XUnit,则可以通过扩展fact属性来使用以下方法as described by Jimmy Bogard

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

然后您可以按如下方式使用它:

[RunnableInDebugOnly]
public void Test_RunOnlyWhenDebugging()
{
    //your test code
}
相关问题