Share Expensive Object Between Tests By IClassFixture

When XUnit run a test method, it’s going to create a new object of our test class for each and everyone of our test method. This can create a problem when the creation of the object is expensive and slow our tests down. But there’s a solution to it, we can use IClassFixture to share an specific instance to example SUT between all of our methods. In this post I’m going to show you how you can use IClassFixture to make our test class to use only once instance for each test.

Test Class Without Using IClassFixture

Let’s assume we have this class which takes a long time to create an instance of.

So we create a test class for our system under test, something like the following.

Now the problem is, for every test in SuperHeavyWeightTests class, we create a new instance of SuperHeavyWeight. That means our three test takes 6 second only to create an instance of SuperHeavyWeight class. That’s because XUnit run the test class constructor per test case in that class. But threre’s a simple fix to this problem which is using IClassFixture to share an instance of our SUT between all of these test cases.

Using IClassFixture to Share the Instance

The first thing we need to do it to create a class fixture for our SUT and use that in our test class instead.

The class SuperHeavyWeightFixture is what we’re going to use instead of our SUT class. So we change the SuperHeavyWeightTests to this.

First we inherit from IClassFixture and pass the fixture that we created previously inside its generic type argument. Now all we have to do it take a dependency to SuperHeavyWeightFixture and replace our test codes to use the fixture instead of using SUT directly.

Now when the XUnit framework runs the test, it’s going to use the fixture for all of our three tests. Another important thing to note is that if our class has some kind of shared field, and we were using it per instance, it need to change. Because we don’t create a news instance of our SUT anymore.

Summary

In this post I explained what is IClassFixture in Xunit framework. We also saw how we can use it to share a SUT instance between all of our test methods when object creation is an expensive process.

Share...
 

Hamid Mosalla

Hi, I'm Hamid ("Arman"). I'm a software developer with 8+ years of experience in C#, .NET Core, Software Architecture and Web Development. I enjoy creating dev tools, contributing to open-source projects, and sharing insights on my blog. Outside of tech, I’m into indie cinema, classical music and abstract art.

 

One thought on “Share Expensive Object Between Tests By IClassFixture

Leave a Reply

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