xUnit offers the concept of (shared) class fixtures as explained in Shared Context between Tests. What I didn't figure out so far is if there is a way of parametrizing such class fixtures. For example, what if the DatabaseFixture
should be enriched with some test data which depends on the test it's being run against? A test class might want to insert test data but only once and then run all its tests against that database (fixture).
In other words, what if the // ... initialize data in the test database ...
from the documentation (referenced above) also depends on the test? Because not all tests might want to have the same test data. Actually, I even think that many times it's good practice that tests define their own test data to not couple tests on the level of test data.
What I'm doing so far as workaround is to offer a ConfiguredWith
method that takes in a callback that is only being executed once. And in order to do so, I need to lazily postpone the initialization of the test database so that I'm sure that the configuration options are set. Something like:
public class MyDatabaseTests : IClassFixture<DatabaseFixture>
{
DatabaseFixture fixture;
public MyDatabaseTests(DatabaseFixture fixture)
{
this.fixture = fixture;
this.fixture.ConfigureWith(new DatabaseFixtureOptions
{
InitTestData = db => db.Insert(...);
};
}
// ...
}
And this looks rather contrived for something that feels like a standard requirement when writing tests against a database.
And if xUnit doesn't offer this out-of-the-box, maybe someone has a better pattern on how to solve this.
This question seems to go in a similar direction but I'm not necessarily fixed on a solution that has that structure.
Theory
alongMemberData
orClassData
won't suffice your needs? it seems to me that what you are looking for is a set of data that is test dependent (MemberData
/ClassData
) instead of test class-dependent (Shared context:ClassFixture
/CollectionFixture
) – Kerley