【问题标题】:NUnit and [SetUp] in base classes基类中的 NUnit 和 [SetUp]
【发布时间】:2013-07-15 16:34:25
【问题描述】:

我正在查看一些使用 NUnit 的测试代码,它继承自包含 [SetUp] 属性的基类:

public class BaseClass
{
   [SetUp]
   public void SetUp()
   {
     //do something
   }

}

[TestFixture]
public class DerivedClass : BaseClass
{
  [SetUp]
  public void SetUp()
  {

   //do something else, with no call to base.SetUp()
  }
   //tests run down here.
   //[Test]
   //[Test]
   //etc
}

派生类肯定需要在基类的 SetUp() 方法中完成的工作。

是我遗漏了什么,还是在运行派生类的测试时不会调用基类中的 SetUp() 方法? [SetUp] 属性有什么特别之处可以确保先调用另一个吗?

【问题讨论】:

  • 构造函数是你的朋友。如果您想要附加设置行为 - 使用构造函数,因为它们的语法对此更直观。此外,您还应该考虑jamesnewkirk.typepad.com/posts/2007/09/why-you-should-.html 中的基本原理
  • 对任何遇到此问题的人的另一个提示:确保您的 SetUp 方法是公开的。如果它们是私有的,R# 不会警告你,但它们不会运行。
  • NUnit 2.5+ 的最新答案在这里:stackoverflow.com/a/22099351/532647

标签: c# nunit


【解决方案1】:

在 NUnit 2.5 之前,之前的答案是正确的;一个测试只能有一个 [SetUp] 属性。

从 NUnit 2.5 开始,您可以拥有多个使用 [SetUp] 属性修饰的方法。因此,以下内容在 NUnit 2.5+ 中完全有效:

public abstract class BaseClass
{
    [SetUp]
    public void BaseSetUp()
    {
        Debug.WriteLine("BaseSetUp Called")
    }
}

[TestFixture]
public class DerivedClass : BaseClass
{
    [SetUp]
    public void DerivedSetup()
    {
        Debug.WriteLine("DerivedSetup Called")  
    }

    [Test]
    public void SampleTest()
    {
        /* Will output
         *    BaseSetUp Called
         *    DerivedSetup Called
        */
    }
}

当继承 NUnit 时,总是首先运行基类中的 '[SetUp]' 方法。如果在单个类中声明多个[SetUp]方法,NUnit不能保证执行顺序。

See here for further information.

【讨论】:

    【解决方案2】:

    你只能有一个SetUp 方法。

    一个 TestFixture 只能有一个 SetUp 方法。如果定义了多个,TestFixture 将成功编译,但其测试不会运行。

    http://www.nunit.org/index.php?p=setup&r=2.2.10

    如果您需要在子类中添加额外的设置逻辑,请在父类中将 SetUp 标记为虚拟,覆盖它,如果您希望基类的设置也运行,请调用 base.SetUp()

    public class BaseClass
    {
       [SetUp]
       public virtual void SetUp()
       {
         //do something
       }
    
    }
    
    
    
    [TestFixture]
    public class DerivedClass : BaseClass
    {
      public override void SetUp()
      {
       base.SetUp(); //Call this when you want the parent class's SetUp to run, or omit it all together if you don't want it.
       //do something else, with no call to base.SetUp()
      }
       //tests run down here.
       //[Test]
       //[Test]
       //etc
    }
    

    【讨论】:

    • 谢谢。那么是不是上面的代码不正确,基础的SetUp()方法不会被调用呢?
    • @larryq 您问题中的代码无效,因为您在继承链中有两个具有 [SetUp] 属性的方法。解决方法是只使用一种 SetUp 方法,然后根据需要覆盖它。
    • 我就是这么想的,谢谢。 (上面的代码是从我一直在做的一个项目中粘贴的,我想知道我是否遗漏了什么。)
    • 这对 nUnit >= 2.5 无效,请参阅stackoverflow.com/a/22099351/2881450
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多