Skip to content

Instantly share code, notes, and snippets.

@sdanna
Created July 28, 2015 03:52
Show Gist options
  • Save sdanna/3b8062146443443dff8f to your computer and use it in GitHub Desktop.
Save sdanna/3b8062146443443dff8f to your computer and use it in GitHub Desktop.
Generic XUnit ClassFixture
public class DatabaseFixture<T> : IDisposable
{
public DatabaseFixture<T>()
{
// Do something interesting with the Generic parameter like initialize
// a database dynamically based on generic type.
Db = new SqlConnection("MyConnectionString");
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
}
public SqlConnection Db { get; private set; }
}
public class MyDatabaseTests : IClassFixture<DatabaseFixture<MyDatabaseTests>>, IDisposable
{
DatabaseFixture<MyDatabaseTests> fixture;
public MyDatabaseTests(DatabaseFixture<MyDatabaseTests> fixture)
{
this.fixture = fixture;
}
// ... write tests, using fixture.Db to get access to the SQL Server ...
public void Dispose()
{
fixture.Respawn(); // Respawn logic to clear out your data.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment