Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Test Name in Xunit2

Tags:

.net

xunit2

When I run my tests today with xUnit v2, I typically use a naming convention like:

[Fact(DisplayName= "Method Will Do Something")] public void Method_Will_Do_Something() { }

What extensibility point can I plug into that will allow me set my test display name based on the naming conventions of my test method?

like image 538
cecilphillip Avatar asked May 27 '15 19:05

cecilphillip


People also ask

How do you name a test?

Naming your tests The name of your test should consist of three parts: The name of the method being tested. The scenario under which it's being tested. The expected behavior when the scenario is invoked.

What is IClassFixture in xUnit?

Important note: xUnit.net uses the presence of the interface IClassFixture<> to know that you want a class fixture to be created and cleaned up. It will do this whether you take the instance of the class as a constructor argument or not.

What is fact in unit testing?

The [Fact] attribute declares a test method that's run by the test runner. From the PrimeService. Tests folder, run dotnet test . The dotnet test command builds both projects and runs the tests. The xUnit test runner contains the program entry point to run the tests.

What is xUnit testing in C#?

xUnit.net is a free, open source, community-focused unit testing tool for the . NET Framework. Written by the original inventor of NUnit v2, xUnit.net is the latest technology for unit testing C#, F#, VB.NET and other . NET languages. xUnit.net works with ReSharper, CodeRush, TestDriven.NET and Xamarin.


2 Answers

The simplest way: Custom fact attribute, discoverer, and test case.

Example: https://github.com/xunit/samples.xunit/tree/master/RetryFactExample

For your custom test case, derive from XunitTestCase and override the Initialize() method. After calling base.Initialize(), set the DisplayName property appropriately.

You can see the default behavior for XunitTestCase here: https://github.com/xunit/xunit/blob/master/src/xunit.execution/Sdk/Frameworks/XunitTestCase.cs

like image 138
Brad Wilson Avatar answered Sep 22 '22 17:09

Brad Wilson


Create a custom class for your fact

public sealed class MyFactAttribute : FactAttribute
{
    public MyFactAttribute([CallerMemberName] string memberName = null)
    {
        DisplayName = memberName;
    }
}

And use as follows

[MyFact]
public void FileSystemProvider_Sync()
like image 35
Steve Drake Avatar answered Sep 22 '22 17:09

Steve Drake