Skip to content

Instantly share code, notes, and snippets.

@bradwilson
Last active October 8, 2022 04:12
Show Gist options
  • Save bradwilson/8423477 to your computer and use it in GitHub Desktop.
Save bradwilson/8423477 to your computer and use it in GitHub Desktop.
Using test collections in xUnit.net v2

Test collections are the test grouping mechanism in xUnit.net v2. They serve two purposes:

  1. They delineate the "parallelism" boundary; that is, tests in the same collection will not be run in parallel against each other;
  2. They offer collection-wide fixtures through the use of ICollectionFixture<TFixtureType>.

The simplest way to use test collections is simply by name. Put two classes into the same named collection, and they can derive benefit #1 above:

[Collection("MyCollection")]
public class TestClass1
{
    // ... tests here ...
}

[Collection("MyCollection")]
public class TestClass2
{
    // ... tests here ...
}

In order to derive benefit #2, you must declare a collection class, so that you have a centralized location to place the ICollectionFixture interface. Test classes continue to use the [Collection] attribute:

public class MyFixture
{
    // Uses ctor and IDisposable.Dispose to setup/cleanup
}

[CollectionDefinition("MyCollection")
public class CollectionClass : ICollectionFixture<MyFixture> { }

[Collection("MyCollection")]
public class TestClass1
{
    // ... tests here ...
}

[Collection("MyCollection")]
public class TestClass2
{
    // ... tests here ...
}

The collection fixture will be created once before running any test in the collection, and destroyed after all tests in the collection have been run. If the tests need access to the fixture, they can take it via their constructor:

[Collection("MyCollection")]
public class TestClass1
{
    public TestClass1(MyFixture fixture)
    {
    }

    // ... tests here ...
}
@azkurban
Copy link

azkurban commented Sep 4, 2020

This feature is awesome, and totally nails a scenario I'm trying to solve. I'm having trouble getting the fixtures to be picked up though. The visual studio and console runners are both failing my tests with:

Result Message: The following constructor parameters did not have matching fixture data: ParentChildBeaconServiceTestFixture serviceFixture

My versions in use are:

  <package id="xunit.core" version="2.0.0-beta4-build2738" targetFramework="net45" />
  <package id="xunit.runner.visualstudio" version="0.99.8" targetFramework="net45" />

Would you expect the v2 functionality (in particular ICollectionFixture) to be available and stable via the current VS runner?

Cheers,

Eddie

Hey Guys, is there someone who answered Eddie's question since 2014? I have the same problem with VS2019
Thanks,
Azamat

@mufasalg0
Copy link

Is there a way to run them in order? (Test Classes)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment