本文介绍了基类中的NUnit和[SetUp]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking at some test code using NUnit, which inherits from a base class containing a [SetUp] attribute:

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()方法中完成工作.

The derived class will certainly need the work done in the base class' SetUp() method.

我是否缺少某些内容,还是在运行派生类的测试时不调用基类中的SetUp()方法?[SetUp]属性有什么特别之处,可以确保其中一个在另一个之前被调用?

Am I missing something, or will the SetUp() method in the base class not be called when the derived class's tests are run? Is there something special with the [SetUp] attribute that ensures one will be called before the other?

推荐答案

您只能使用一个 SetUp 方法.

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

如果您需要在子类中添加其他设置逻辑,请在父类中将 SetUp 标记为虚拟,将其覆盖,并在以下情况下调用 base.SetUp()您也要运行基类的设置.

If you need to add additional setup logic in a child class, mark SetUp as virtual in your parent class, override it, and call base.SetUp() if you want the base class's setup to run, too.

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
}

这篇关于基类中的NUnit和[SetUp]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 23:22