Parameterizing Unit Tests using xUnit

xUnit allows our unit test to use parameters, which allows us to test our code for multiple scenarios without needing to write multiple methods with same content.

Let’s look at example from previous lesson

Here we test if 3 + 9 equals 12.

But what if we wanted to test our Add method for multiple scenarios?


We could use InlineData Attribute.

InlineData Attribute allows us to run our test with input parameters, and passes those parameters to test method using params object[] data.

We are not done yet.

Compiler is not happy and we are getting error : Fact methods cannot have parameters.

Simple solution is to replace Fact Attribute with Theory Attribute

Now, when we run our unit test we can see that same test method ran 3 times an all test have passedĀ  šŸ™‚

Also note that we can also see input parameters!

Beginners guide to xUnit

To add xUnit to your project open up NuGet package manager

(Tools -> NuGet Package manager -> Manage Nuget packages for Solution


Right-click References of your project and chose Manage Nuget packages)

xUnit Nuget installation





And find xUnit package byĀ  James Newkirk and Brad Wilson and press install.

To use xUnit in your project you do not have to decorate your class with TestClass attribute!

You must only decorate your methods with Fact Attribute.

Also be sure to referenceĀ Xunit assembly in your class file because xUnit’s Assert class is from that namespace.

If tests you write do not show in Test explorer, open NuGetĀ  packet manager and add xunit.runner.visualstudio package (do not be confused if you seeĀ Visual Studio 2012+ in description, it is just saying that this is for version from VS 2012 an onwards).

There is also neat trick to modify name of your tests. By default Test explorer is showing xUnit’s test names in format Class.Method, but you can only display test Method names. Add new json file to root of project and name it “xunit.runner.json” and open properties of that file and under “Copy to Output Directory”Ā  option chose “Copy if newer”.













Open under xunit.runner.json file and under Schema input “https://xunit.github.io/schema/v2.2/xunit.runner.schema.json”, then inside brackets type “methodDisplay”: “method”.





Happy unit testing šŸ™‚

© 2021 LearnC#WithDarko

Theme by Anders NorenUp ↑