Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created January 11, 2013 23:09
Show Gist options
  • Select an option

  • Save jarrettmeyer/4514742 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/4514742 to your computer and use it in GitHub Desktop.
public class DBTest : IDisposable
{
private DataContext dataContext;
public DBTest()
{
dataContext = new DataContext();
}
public void Dispose()
{
if (dataContext != null)
dataContext.Dispose();
}
public void StartDBTest()
{
DeleteDatabaseIfExists();
CreateDatabase();
RunFixtures();
}
public void EndDBTest()
{
DeleteDatabaseIfExists();
}
private void DeleteDatabaseIfExists()
{
if (dataContext.Database.Exists)
dataContext.Database.Delete();
}
private void CreateDatabase()
{
dataContext.Database.CreateDatabase();
}
private void RunFixtures()
{
// Here, put any inserts that need to happen. In most
// scenarios, a completely empty database just will not
// work. You have to expect some basic amount of data.
}
}
public abstract class DBTestContext
{
protected DBTest dbTest;
[TestFixtureSetUp]
public virtual void BeforeAllTests()
{
using (dbTest = new DBTest())
{
dbTest.StartDBTest();
}
}
[SetUp]
public virtual void BeforeEachTest()
{
dbTest = new DBTest();
}
[TearDown]
public virtual void AfterEachTest()
{
if (dbTest != null)
dbTest.Dispose();
}
[TestFixtureTearDown]
public virtual void AfterAllTests()
{
using (dbTest != null)
{
dbTest.EndDBTest();
}
}
}
public class SampleTest : DBTestContext
{
public override void BeforeEachTest()
{
// Code here will be run before each test.
base.BeforeEachTest();
}
public override void AfterEachTest()
{
// Code here will be run after each test.
base.AfterEachTest();
}
[Test]
public void TestThatRecordIsInserted()
{
// Depending on how many other tests you have, and what order they're run
// we cannot guarantee that the Employees table is empty.
int initialCount = dataContext.Employees.Count();
dataContext.Employees.Add(new Employee { FirstName = John, LastName = Doe });
dataContext.SaveAllChanges();
int newCount = dataContext.Employees.Count();
Assert.Equal(newCount, initialCount + 1);
// This is why your tests have to be single threaded. What if you have two tests
// performing inserts, and just by chance they run in such a way that this test
// breaks. You could test newCount > initialCount, but that's not as specific.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment