AssemblyInitialize, AssemblyCleanup and Sharing State Between Test Classes in XUnit

We have covered quite a bit in this series on migrating from MSTest to XUnit and we have not even got to the coolest bit yet; data-driven theories. If that is what you are waiting for, you will have to wait a little longer. Before we get there, I want to cover one last piece of test initialization as provided in MSTest by the AssemblyInitialize and AssemblyCleanup attributes.

As we saw in previous posts, we can use the test class constructor and Dispose() for TestInitialize and TestCleanup, and IClassFixture and fixture classes for ClassInitialize and ClassCleanup.  For the assembly equivalents, we use collections and the ICollectionFixture interface.

A collection is defined by a set of test classes and a collection definition. A test class is designated as being part of a specific collection by decorating the class with the Collection attribute, which provides the collection name. A corresponding class decorated with the CollectionDefinition attribute should also exist as this is where any collection fixtures are defined. All classes that share the same collection name will share the collection fixtures from which the definition class derives.

public class MyFirstFixture
{
    public MyFirstFixture()
    {
        // Some initialization
    }
}

public class MySecondFixture : IDisposable
{
    public MySecondFixture()
    {
        // Some initialization
    }

    public void Dispose()
    {
        // Some cleanup
    }
}

[CollectionDefinition("MyCollection")]
public class MyCollectionDefinition : ICollectionFixture<MyFirstFixture>, ICollectionFixture<MySecondFixture>
{
    //Nothing needed here
}

[Collection("MyCollection")]
public class TestClass1
{
    [Fact]
    public void TestMethod1()
    {
        // Do some testing
    }
}

[Collection("MyCollection")]
public class TestClass2
{
    [Fact]
    public void TestMethod1()
    {
        // Do some more testing
    }
}

The example code above shows a collection definition with two fixtures and two test classes defined as part of that collection. Note how the fixtures control initialization and cleanup using constructors and IDisposable 1 . We can modify those classes to reference the collection fixtures just as we did with class-level fixtures; by referencing the fixture in the constructor arguments as shown here.

[Collection("MyCollection")]
public class TestClass1
{
    public TestClass1(MySecondFixture fixture)
    {
        // Do something with the collection fixture
    }

    [Fact]
    public void TestMethod1()
    {
        // Do some testing
    }
}

I really like this approach over the attributed static methods of MSTest. This seems to more easily support code reuse and makes intentions much clearer, separating the concerns of tests (defined in the test class) from fixtures (defined by the fixture types). The downside is that fixture types do not get access to the ITestOutputHelper interface so if you want your fixtures to output diagnostic information, you should consider a logging library like Common.Logging. Also, your fixture types must be in the same assembly as your tests. Of course, that doesn't preclude the fixtures from using types outside of the assembly, so you can always put shared implementation between test assemblies in some other class library.

And that brings our migration of shared initialization to a close. You can find more information on sharing context across tests on the xunit site. Next up, we will look at data-driven tests. Thank you for your time. If you have any questions, please leave a comment.

  1. A fixture type can used with IClassFixture<T> or ICollectionFixture<T> []

TestContext Equivalence in XUnit2, or How Do I Write Output in XUnit2?

So far, in discussing the migration of MSTest to XUnit2, I have only touched on the basics. First, I covered using the XUnitConverter to make the transition a little easier, then I provided an overview of how the basic MSTest concepts tests, test initialization, and test cleanup were supported. In this post I want to look at the confusing dumping group that is TestContext. My goal with these posts is to provide useful search results for those looking for information on XUnit, especially when migrating from MSTest. For a moment though, let me rant about TestContext.

I am sure that there are people out there who totally get all the values and functions TestContext provides; however, other than writing log messages, I have found the TestContext properties wildly confusing and unhelpful. I somehow doubt I am alone. Not only that, but the inconsistent ways a method gets access to the TestContext dependent on whether it is an instance method or a static method makes things confusing1.

TestContext Properties

TestContext Properties

TestContext Methods
TestContext Methods

Looking at the documentation from MSDN (shown above), it should be clear to anyone that TestContext is trying to do a lot of different things. There are methods in there for outputting things to the test trace messages, adding results files, and running timers, and properties for getting all sorts of information from directories for results, to the name of the test, to things related to data driven tests. Overall, it is convoluted and confused; do you know the difference between ResultsDirectory, TestResultsDirectory, and TestRunResultsDirectory? Even after working with MSTest for nearly 10 years, I could not begin to tell you. In my opinion, TestContext does too much and is almost always unintuitive to use, so how does XUnit tackle these things?

Well, first of all, XUnit does not even begin to replace the timer stuff because, well, there are plenty of timer options available in the .NET framework, so just use one of them.

Second, XUnit manipulates the current directory when running tests, so the location retrieved from Environment.CurrentDirectory will be where the tests are running and where test data will live. We will focus on data-driven testing in another post, but suffice to say that you do not need to decipher pages of documentation or debug tests to understand where to find your test data or where to output your test results (if you have something to output, of course).

Finally, if you want to write to the test output, XUnit provides an interface that you can inject into your constructor for doing just that and only that; ITestOutputHelper.

ITestOutputHelper

Since the XUnit documentation is very helpful on how to use this interface, I won't go into great detail here. However, for those looking to replace TestContext.WriteLine, this is what you need to do.

using Xunit;
using Xunit.Abstractions;

public class MyTests
{
    private readonly ITestOutputHelper _output;

    public MyTests(ITestOutputHelper output)
    {
        _output = output;
    }

    [Fact]
    public void Test1()
    {
        var stringValue = "a thing to output";
        _output.WriteLine($"My string value is \"{stringValue}\"");
    }
}

The test runner observes from the signature of the class constructor that it requires the ITestOutputHelper interface and injects it, making it available throughout the test execution, including during the Dispose method, if present.

Next time, we will take a look at how XUnit tackles sharing initialization across multiple tests. In the meantime, if you are finding these posts useful or have any questions, please leave a comment.

  1. a property called TestContext with public getter and setter for instance methods; or passed as a parameter for static methods []

TestMethod, TestInitialize, and TestCleanup in XUnit2

In the last post, I briefly described how to automatically migrate your MSTest tests to XUnit by using the XUnitConverter utility. Of course, nothing is ever that simple; MSTest has some concepts that XUnit expresses very differently1 like how to share code between tests whether that is setup, fixtures, cleanup, or data. Some of these concepts are implemented differently enough that automating the migration from one to the other would be very difficult if not impossible. However, some of it really is that simple. Before we look at the difficult examples, I thought it would be useful to illustrate how some of the simple concepts map from MSTest to XUnit using an example2.

So, let's look at an MSTest example (contrived, of course):

[TestClass]
public class MyTests
{
    private MemoryStream _stream;

    [TestInitialize]
    public void Initialize()
    {
        _stream = new MemoryStream();
    }

    [TestCleanup]
    public void Cleanup()
    {
        _stream.Dispose();
    }

    [TestMethod]
    public void Test1()
    {
        //Arrange
        //Act
        //Assert
    }

    [TestMethod]
    public void Test2()
    {
        //Arrange
        //Act
        //Assert
    }
}

Clearly, I cheated by not actually making the tests do anything, but the content of the test methods is mostly irrelevant; you set some stuff up, you do something, and you assert a result–it's all the same regardless of the test framework. However, this is a simple example of a test class written for the MSTest framework. There are attributes to tell the framework that the class is a test class, which methods inside of it are test methods, and which methods should be called before and after each test. In this case, our test initialization creates a stream, which is then disposed of in the cleanup method; each test method would get sandwiched in the middle.

After converting to XUnit with the converter tool, the same class will look something like this:

public class MyTests : IDisposable
{
    private MemoryStream _stream;

    public MyTests()
    {
        _stream = new MemoryStream();
    }

    public void Dispose()
    {
        _stream.Dispose();
    }

    [Fact]
    public void Test1()
    {
        //Arrange
        //Act
        //Assert
    }

    [Fact]
    public void Test2()
    {
        //Arrange
        //Act
        //Assert
    }
}

There are a few things that happened.

  1. The class no longer has an attribute. XUnit knows the class is a test class because it contains tests3.
  2. The tests are decorated with a [Fact] attribute, which is equivalent to [TestMethod].
  3. The [TestInitialize] and [TestCleanup] attributes are gone. Instead, the class constructor is used for test initialization and the Dispose method along with deriving from IDisposable indicates that there is test cleanup code.

Overall, I love how the XUnit syntax works with C# syntax and .NET idioms in declaring tests. Not only does this reduce the ceremony around defining tests by reducing the various decorators, but it also allows for cleaner coding practices. For example, we can now correctly mark our memory stream member variable as readonly.

private MemoryStream _stream;

By relying on C# syntax and standard interfaces in this way, the lifecycle of a test is clearer too; XUnit will construct and dispose the class for each test in the class, making it easy to see how each test will run. This idiomatic way of declaring tests allows for separation of concerns, keeping test classes light and focused. This will be illustrated when we later look at other concepts in MSTest like [ClassInitialize] and [ClassCleanup], TestContext, and [DeploymentItem], and how XUnit tackles the problems these concepts solved.

  1. and for good reasons, IMHO []
  2. XUnit documentation has a handy table but I don't think it's as illustrative as it could be []
  3. why MSTest did not make assumptions like this, I do not know []