Created
November 12, 2013 21:24
-
-
Save gabrieljoelc/7438990 to your computer and use it in GitHub Desktop.
Good pattern for creating test contexts. From http://iamnotmyself.com/2011/12/18/test-driven-evolutionary-design-with-entity-framework/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data.Common; | |
using System.Data.Entity.Migrations; | |
using TestingEntityFramework.Core.Extensions; | |
using TestingEntityFramework.Data; | |
using TestingEntityFramework.Data.Migrations; | |
namespace TestingEntityFramework.Tests.Helpers | |
{ | |
public class TestDataContextFactory | |
{ | |
private const string ConnectionString = "Data Source={0}.sdf"; | |
private const string ProviderName = "System.Data.SqlServerCe.4.0"; | |
public static DataContext Build() | |
{ | |
var databaseName = DateTime.Now.Ticks.ToString(); | |
StandUpTestDatabase(databaseName); | |
return CreateDataContext(databaseName); | |
} | |
private static DataContext CreateDataContext(string databaseName) | |
{ | |
var connection = DbProviderFactories.GetFactory(ProviderName).CreateConnection(); | |
connection.ConnectionString = ConnectionString.FormatWith(databaseName); | |
return new DataContext(connection); | |
} | |
private static void StandUpTestDatabase(string databaseName) | |
{ | |
var config = new Configuration | |
{ | |
ConnectionString = ConnectionString.FormatWith(databaseName), | |
ConnectionProviderName = ProviderName, | |
AutomaticMigrationsEnabled = true | |
}; | |
new DbMigrator(config).Update(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using NUnit.Framework; | |
using TestingEntityFramework.Core; | |
using TestingEntityFramework.Data; | |
using TestingEntityFramework.Tests.Helpers; | |
namespace TestingEntityFramework.Tests | |
{ | |
[TestFixture] | |
public class UserPersistenceTests | |
{ | |
private DataContext context; | |
[SetUp] | |
public void SetUp() | |
{ | |
context = TestDataContextFactory.Build(); | |
} | |
[Test] | |
public void can_persist_user() | |
{ | |
var user = new User { Id = -1, FirstName = "Dirk", LastName = "Diggler", Email = "[email protected]"}; | |
context.Users.Add(user); | |
context.SaveChanges(); | |
Assert.That(user.Id, Is.EqualTo(1)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment