Skip to content

Instantly share code, notes, and snippets.

@luisrudge
Created May 8, 2014 13:54
Show Gist options
  • Save luisrudge/242030b3f58b4993519b to your computer and use it in GitHub Desktop.
Save luisrudge/242030b3f58b4993519b to your computer and use it in GitHub Desktop.
testing entity framework C#
public abstract class DbTest {
protected MyDbContext Db;
private DbConnection _connection;
protected abstract DbConnection DbConnection { get; }
[SetUp]
public virtual void Setup() {
CreateContext(true);
Db.Database.CreateIfNotExists();
Db.Database.Initialize(true);
}
private void CreateContext(bool isNew) {
if (_connection == null || isNew) {
_connection = DbConnection;
}
Db = new MyDbContextb(_connection);
}
[TearDown]
public void TearDown() {
Db.Database.Delete();
Db.Dispose();
}
protected void ExecuteAndSave(Action a) {
a();
Db.SaveChanges();
CreateContext(false);
}
}
public abstract class InMemoryDbTest : DbTest {
protected override DbConnection DbConnection {
//this uses Effort
get { return DbConnectionFactory.CreateTransient(); }
}
}
public abstract class LocalDbTest : DbTest {
protected override DbConnection DbConnection {
get {
return new SqlConnection(@"Data Source=(LocalDb)\Projects;Initial Catalog=MyDb.Tests;Integrated Security=true");
}
}
}
public abstract class SqlExpress : DbTest {
protected override DbConnection DbConnection {
get {
return new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MyDb.Tests;Integrated Security=true");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment