Skip to content

Instantly share code, notes, and snippets.

@callumj
Created March 11, 2014 09:31
Show Gist options
  • Save callumj/9482396 to your computer and use it in GitHub Desktop.
Save callumj/9482396 to your computer and use it in GitHub Desktop.
TearUp/Down databases in NUnit tests

Database helper for NUnit tests

I've found the need to interact with an actual database context during my NUnit tests (as opposed to abstracting away), I couldn't find any ways to achieve this so I've written my own simple TestHelper.

Basically this give you access to TestHelper.testContext, which will create the context and migrate the test database for the first time.

namespace SomeNamespace
{
[SetUpFixture]
public class TestHelper
{
private static DataContext _testContext { get; set; }
// provides on-demand dataabse usage
public static DataContext testContext
{
get
{
if (_testContext == null)
SetupDatabase();
return _testContext;
}
set
{
_testContext = value;
}
}
public static void SetupDatabase()
{
SetupContext();
var conf = new Migrations.Configuration();
conf.TargetDatabase = new DbConnectionInfo(TestHelper.testContext.Database.Connection.ConnectionString, "System.Data.SqlClient");
var migrator = new DbMigrator(conf);
var pending = migrator.GetDatabaseMigrations();
try
{
migrator.Update();
}
catch { }
}
public static void SetupContext()
{
TestHelper._testContext = new DataContext("Data Source=.\\SQLEXPRESS;Initial Catalog=SOMEDB;Integrated Security=True;MultipleActiveResultSets=True");
}
[TearDown]
public void CleanUpDatabase()
{
if (TestHelper._testContext != null)
TestHelper.testContext.Database.Delete();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment