开发者

Nunit: Is it possible to have tests appear nested

I want to test one method that has a high cyclomatic 开发者_C百科complexity (sigh) and I would like to have a class within test class so that a method test class appears as a node in the tree. Is it possible with Nunit and how?

 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.....

  }
}


You can do it with nested classes, very similar to the example code in your question.

The only difference to your code is that the outer class doesn't need the [TestFixture] attribute if it's only used for the structure and doesn't have tests itself.

You can also have all inner classes share a Setup method, by putting it into the outer class and having the inner classes inherit from the outer class:

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()
            {
            }
        }
    }
}

In the NUnit GUI, this test class will look like this:

Nunit: Is it possible to have tests appear nested


I've used (abused?) namespaces to get this behavior:

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()
        {          
        }
    }
}

Which will give you:

MyEntityTests
- MyComplexMethodTests
  - when_some_condition_than
    - it_should_do_something
  - when_some_other_condition_than
    - it_should_do_something_else

In this case I'll normally use the TestFixture to define the context for the test.


It sounds like you have one class you want to test, but you have two sets/types of tests to run. The easiest way to do that might be to create two TestFixtures, one for each. Another way to do it is to place each test into a Category.

Edit: If all of the tests are on the same method, one option is to use the TestCase attribute and specify the parameters for each test (as well as the expected result.) The GUI will nest each set of TestCase parameters under a single instance of that test name. This assumes all of your tests will behave similarly, meaning the same basic Asserts or ExpectedExceptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜