Testing Entity Framework with fixtures
asp.net-mvc-3, c#, entity-framework, tdd, unit-testing
Solution
In EF5 new concept has been introduced, called Migrations. You probably used to use something similar in Rails or Django applications.
Migration is a class, that has several functions to upgrade / downgrade the version of DB.
public partial class VoteTime : DbMigration
{
public override void Up()
{
AddColumn("Votes", "Time", c => c.DateTime(nullable:false, defaultValue:DateTime.UtcNow));
}
public override void Down()
{
DropColumn("Votes", "Time");
}
}
You also, have to setup DbContext and DbMigrationsConfiguration configuration classes to allow code first approach to work.
For testing purposes you need to introduce, `TestDatabaseInitilizer`
public class TestDatabaseInitilizer : DropCreateDatabaseAlways<DbContext>
{
}
It would be responsible for initialization of test database for unit tests.
Finally, you should design your test code to setup the context.
public class SomeRepositoryTests
{
private DbContext _context;
[SetUp]
public void Setup()
{
Database.SetInitializer(new TestDatabaseInitilizer());
_context = new DbContext("TestContext");
_repository = new SomeRepository(_context);
}
[Test]
public void should_return_some_entities()
{
Assert.That(_repository.Get(), Is.Not.Null);
}
}
The setup code could be moved to base class, if required.
Problem
One of the things I like about Rails' and Django's testing approach is their support of using fixtures to set up a database before each test is run. In the past, I've used strict unit tests in conjunction with a mocked repository to test my code, but I'd love to have something that's as easy to use as the aforementioned testing approaches in order to do integrated testing. I've heard some talk of this type of support with code-first and EF 5, but I don't know if it rises to the level of what Rails and Django provide. Surely there's something comparable out there. Any information would be appreciated!