Nunit:是否可以将测试显示为嵌套

epi*_*tka 13 c# nunit

我想测试一个具有高圈复杂度(叹气)的方法,我想在测试类中有一个类,以便方法测试类作为树中的节点出现.是否有可能与Nunit和如何?

 MyEntityTests
 |
 L_ MyComplexMethodTests
    L when_some_condition_than
    L when_some_other_condition_than

[TestFixture]
public class MyEntityTests
{
  [TestFixture]
  public class MyComplexMethodTests
  {
    [Test]
     public void when_some_condition_than() {} 
   etc.....

  }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*cht 18

您可以使用嵌套类来完成它,与您问题中的示例代码非常相似.

与代码的唯一区别在于,如果外部类[TestFixture]仅用于结构并且本身没有测试,则外部类不需要该属性.

您还可以让所有内部类共享一个Setup方法,方法是将它放入外部类并让内部类继承自外部类:

using NUnit.Framework;

namespace My.Namespace
{
    public class MyEntityTests
    {
        [SetUp]
        public void Setup()
        {
        }

        [TestFixture]
        public class MyComplexMethodTests : MyEntityTests
        {
            [Test]
            public void when_some_condition_than()
            {
            }

            [Test]
            public void when_some_other_condition_then()
            {
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在NUnit GUI中,此测试类将如下所示:

NUnit GUI

  • Resharper的测试运行器似乎认识到但忽略了以这种方式构建的任何测试.:\ (3认同)

Eri*_*ock 6

我使用(滥用?)命名空间来获取此行为:

namespace MyEntityTests.MyComplexMethodTests
{
    [TestFixture]
    public class when_some_condition_than
    {
        [Test]
        public void it_should_do_something()
        {           
        }
    }

    [TestFixture]
    public class when_some_other_condition_than
    {
        [Test]
        public void it_should_do_something_else()
        {          
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个会给你:

MyEntityTests
- MyComplexMethodTests
  - when_some_condition_than
    - it_should_do_something
  - when_some_other_condition_than
    - it_should_do_something_else
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我通常会使用TestFixture来定义测试的上下文.