Change the name of the NUnit test

I want my unit tests to be based on a NUnit

framework named by a more human readable in Visual Studio test explorer.

For example, instead of Test_Case_1

or, TestCase1

I would like to have something like Test Case #1, Category: First, Category: Second

(by assigning values ​​from attributes [Category]

), with spaces and characters not allowed in method names.

I know it is possible in xUnit

, but I cannot use it as I am using my own settings which I was not able to implement with the xUnit

framework.

Is it possible to rewrite unit test display name with NUnit

? So far I can see FullName

TestDetail

there is a private setter in the field .

Are there any other ways or approaches to change the display name for tests NUnit

?

+3


source to share


2 answers


This is supported if you are using parameterized tests, you can specify TestName

when adding the attribute TestCase

.

If you are not using TestCase , you can use it as a less ideal job to achieve what you are trying to do. Thus, you will declare your test like this:

[TestCase(null,TestName="Test Case #1, Category: First, Category: Second")]
public void TestCase(object ignored)

      



This is not ideal because it is not programmatic, so you need to manually enter the test name rather than generate it from the test method attributes. You must also pass a parameter to the method, which is ignored

and null

. You can of course start using parameterized tests, in which case you will be passing the actual value to your tests.

[TestCase(5,TestName="Test Case #1, Category: First, Category: Second")]
public void TestCase(int someInput) {
    Assert.AreEqual(5, someInput);
}

      

+2


source


You can create your own Name attribute:

// I used the same namespace for convenience
namespace NUnit.Framework
{
    public class NameAttribute  : NUnitAttribute, IApplyToTest
    {
        public NameAttribute(string name)
        {
            Name = name;
        }

        public string Name { get; set; }

        public void ApplyToTest(Test test)
        {
            test.Properties.Add("Name", Name);
        }
    }
}

      

Then you use it like a normal NUnit property (just like category and description).



[Test, Name("My Awesome Test"), Category("Cool.Tests"), Description("All cool tests")]
public void Test313()
{
    // Do something
}

      

You can see the data in TestContext:

if (TestContext.CurrentContext.Test.Properties.ContainsKey("Name"))
{
    name = TestContext.CurrentContext.Test.Properties.Get("Name") as string;
}

      

+2


source







All Articles