xUnit: Share an SUT Instance Between Two Class Using Collection

In my previous post I talked about how we can Share Expensive Object Between Tests By Using IClassFixture. My previous post is about situations when we want to share a class instance between all test methods. Because a test class is created once per test method so its constructor is executed per test methods. But sometimes we have to split our tests for an SUT between two classes to make it more maintainable. We  can do this using Collection and CollectionDefinition attributes.

But the problem is we might have an expensive to create SUT that’s going to be used for couple of classes separately. We have to find a way to share the SUT instance between our test classes. So in this post I’m going to describe how we can share an instance of SUT or any other dependency between different test classes.

Make Two Test Class Part of the Same Collection

Let’s say we have a dependency from the below class in both of our test classes.

What we want to achieve is to create the SuperHeavyWeightFixture class only once for each class. The first thing we need to do is to apply Collection attribute to our test classes. In this case both of our classes use an instance of SuperHeavyWeightFixture which we need to share between both.

Both of the above class have the collection attribute named “Heavy Tests Collection”. The next step is to create collection definition that specify what we need to share between these two classes.

Create a CollectionDefinition

Now we need to create a class and apply CollectionDefinition attribute to it. We also need to pass in the name of the collections we want to describe which in this case is “Heavy Tests Collection”.

In the above code we applied the CollectionDefinition attribute to HeavyTestCollection class. We also need to inherit from the ICollectionFixture and pass in the class we want to share an a generic argument which in this case is SuperHeavyWeightFixture. Now if we put a break point on SuperHeavyWeightFixture constructor, we’ll see it’ll be hit only once.

Summary

Sometimes we have a dependency on an expensive to create dependency and we need to share an instance of that between two separate classes. We can achieve this using Collection and CollectionDefinition attributes. In this post I described how to use them to make our tests faster to run and more maintainable.

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.

 

Leave a Reply

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