代码之家  ›  专栏  ›  技术社区  ›  Julien Poulin

如何使单元测试仅在调试模式下运行?

  •  10
  • Julien Poulin  · 技术社区  · 15 年前

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

    4 回复  |  直到 15 年前
        1
  •  16
  •   Kobi    9 年前

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

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

    也许是因为你的处境

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

        2
  •  6
  •   Stefan Steinegger    15 年前

    试试这个:

    #if DEBUG
    
    // here is your test
    
    #endif
    
        3
  •  6
  •   Tamas Czinege    15 年前

    如果您使用的是NUnit,则可以将单元测试方法设置为有条件的:

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

    这样,它将只在调试版本中执行。我对VisualStudio单元测试没有太多经验,但我非常确定这在VS中也应该适用。

    编辑 Eric Lippert's excellent article here .

        4
  •  1
  •   Thomas Mulder Harikasai    8 年前

    如果您使用的是XUnit,那么可以使用以下方法 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
    }
    
        5
  •  1
  •   Jan Szymanski    6 年前

    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
    }