Passing collection fixture to a class fixture #2699
-
Is it possible to pass a collection fixture to a class fixture? I have some tests where I have some data initialization where order matters and there is shared setup across the whole collection and then specific configuration for different tests. This made me think it might be useful to have a collection fixture that can then be passed to the different class fixtures. I can't find anything on this in the documentation. Is there maybe a better design choice then this? Is this possible? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
https://xunit.net/docs/shared-context Note that you cannot control the order that fixture objects are created, and fixtures cannot take dependencies on other fixtures. If you have need to control creation order and/or have dependencies between fixtures, you should create a class which encapsulates the other two fixtures, so that it can do the object creation itself. I'm guessing this answers my question but I wasn't certain since the creation order for class vs collection fixtures is fundamentally different. |
Beta Was this translation helpful? Give feedback.
-
Yes, this does work as you'd expect: using Xunit;
public class Fixture1
{
public static int CtorCount = 0;
public Fixture1() => CtorCount++;
}
public class Fixture2
{
public Fixture1 F1;
public Fixture2(Fixture1 f1) => F1 = f1;
}
[CollectionDefinition(nameof(MyCollection))]
public class MyCollection : ICollectionFixture<Fixture1>
{ }
[Collection(nameof(MyCollection))]
public class UnitTest1 : IClassFixture<Fixture2>
{
Fixture2 f2;
public UnitTest1(Fixture2 f2) => this.f2 = f2;
[Fact]
public void Test1()
{
Assert.NotNull(f2.F1);
Assert.Equal(1, Fixture1.CtorCount);
}
}
[Collection(nameof(MyCollection))]
public class UnitTest2 : IClassFixture<Fixture2>
{
Fixture2 f2;
public UnitTest2(Fixture2 f2) => this.f2 = f2;
[Fact]
public void Test2()
{
Assert.NotNull(f2.F1);
Assert.Equal(1, Fixture1.CtorCount);
}
} Note that the discussion about "creation order" is when class fixtures depend on class fixtures (or collection fixtures depend on collection fixtures). Since collection fixtures and class fixtures are created at different times by definition, you can always be sure that collection fixtures are created before class fixtures. |
Beta Was this translation helpful? Give feedback.
Yes, this does work as you'd expect: