XUnit – Part 7: Categorizing Tests with xUnit Trait

Sometimes we only need to run a specific kind of tests and not others. In order to be able to do that we need some mechanism to categorize our tests. xUnit has a built in mechanism for this called Trait. In this post I’m going to show how we can use it to categorize our tests. I’m also going to introduce some  third party library that make things easier.

Using Naming Convention To Categorize Our Tests

The simplest way to make our test more accessible is to change how we name our tests. Suppose we want to the a class called SampleClass. One thing that can help us to be able to find the test in this class better is to prefix the name of our test with the name of the class we’re testing (System Under Test). For example instead of using Add_Always_ReturnsTheCorrectResult we can use something like SampleClass_Add_Always_ReturnsTheCorrectResult. There are a lot of opinions about how we can name our tests, but I find this one is the most practical at least for me.

Categorizing Using xUnit Trait

The standard way of categorizing tests in xUnit is by using Trait. It can be used like so.

The Trait attribute receive two arguments. The first is the actual name of the category and the second argument is the subsection whiting the category. For example we have the category UI as a key and for value we have Front and Back. So we have the UI category that have two sections, front end tests and back end tests. Here’s how the test explorer show it.

While I admit that the arguments for Trait is a little counter intuitive, I think this was the reason they accepted two arguments. But that kind of doesn’t make sense.

Using Third Party Improved Trait

If you think using Trait is counter intuitive there’s also another third party library called Xunit.Categories. It improves over the Idea of Traits to make it easier to use.

Running Test in Console Based On Trait

Last but not the least is running our tests in console based on Trait. Here’s an example showing how we can filter based on Traits.

dotnet test --filter "Category=UI&Category!=Integration"

Here we say that we only want to run the tests with Category UI and not Integration. Here’s the documentation about other options available when we want to filter our tests.

Summary

In this post we saw how we can use Trait in xUnit to categorize our test. We also saw how we can make our tests more accessible by naming our tests. Lastly I introduced some third party library to make it easier. The code sample related to this blog post can be found in this repository.

Share...
 

Hamid Mosalla

Hi, I'm Hamid Mosalla, I'm a software developer, indie cinema fan and a classical music aficionado. Here I write about my experiences mostly related to web development and .Net.

 

Leave a Reply

Your email address will not be published.