xUnit BeforeAfterTestAttribute: How to Run Code Before And After Test

Sometimes we need to run a piece of custom code before and after a test and set of tests. One example of this might be when we want to change the thread culture. In this case we change it before test start to run and restore it to its original after test is finished. One thing we can do is to use BeforeAfterTestAttribute to do it. So in this post I’m going to show you how you can use this attribute and we’ll see some example that demonstrate the specific of how it can be used.

Creating the BeforeAfterTestAttribute Attribute

First thing we need to do it to create an attribute that inherit from BeforeAfterTestAttribute. Then we need to over ride the Before and After method and place the code that we need to run there. Here’s a very simple example.

This is a simple example with only a bare bone of what’s needed to be done. Here’s a more practical example from Brad Wilson’s xunit sample repository.

In above example, we use it to change the culture before test and restore it back to normal after it. Notice also that before and after method has a parameter of type MethodInfo. We can use this parameter to ask information about the running method of possibly change how the method behave.

Now that we saw how we can build an attribute that run code for our before and after test, let’s see how we can use it.

Using the Custom BeforeAfterTestAttribute  Atrribute

To run a piece of code before and after a test, the only thing we need to do is to decorate the class or method with the attribute we just built.

Here’s what happens after we decorate our method and run the test.

It also worth to note that we could run this attribute on a single method or an entire class with sets of methods.


In this post I explained what BeforeAfterTestAttribute is and how it can help us. We saw how we can use it to run a piece of code before and after a test got executed.


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.


One thought on “xUnit BeforeAfterTestAttribute: How to Run Code Before And After Test

Leave a Reply

Your email address will not be published. Required fields are marked *