views:

134

answers:

1

Hi

I am using SQL Server with Entity Framework for a development of web app in .NET 4 with VS2010 RC. I would like to prepare testing database with sample data.

Should I prepare a copy of the real database (say another SQL Server database) for testing, or can I use SQLite in memory for better performance?

If using SQLite, can I use the same model EF has created for SQL Server database? How to migrate schema from SQL Server to in-memory SQLite?

How are you testing your code that uses EF with SQL Server?

Thanks for sharing.

+1  A: 

I use LINQ to Objects and DI.

So let's say I have a service which uses a repository:

public FooService : Service, IFooService
{
    private IFooRepository Repository { get; set; }

    public GetSpecialFoos()
    {
        return from f in Repository.SelectAll()
               where f.IsSpecial
               select f;
    }

    public FooService(IFooRepository repository)
    {
        this.Repository = repository;
    }
}

Now I can use constructor injection to inject a mock repository for testing. Generally, you'd use a DI framework for this. But the important thing is the mock repository can use LINQ to Objects:

public MockFooRepository : IFooRepository
{
     public IList<Foo> Data { get; set; }

     public IQueryable<Foo> SelectAll()
     {
         return Data.AsQueryable();
     }
}

Now I can test:

[TestMethod]
public void GetSpecialFoos_returns_only_special_foos()
{
    var specialId = 1;
    var notSoSpecialId = 2;
    var foos = new List<Foo> 
    {
         new Foo
         {
             Id = specialId,
             IsSpecial = true
         },
         new Foo
         {
             Id = notSoSpecialId,
             IsSpecial = false
         }
    }
    // use a DI framework here instead, in the real world
    var repository = new MockFooRepository
    {
        Data = foos
    };
    var service = new FooService(repository);

    var actual = service.GetSpecialFoos();

    var returned = actual.First();
    Assert.AreEqual(true, returned.IsSpecial);
    Assert.AreEqual(specialId, returned.Id);
}
Craig Stuntz
Thanks. I have to consider using LINQ to Objects as my code operates on entities only through generic repository. Should I simulate the whole repository using predefined objects?
twk
I build a data set per-test when the data is important, and use random data otherwise. L2O is different than L2E (e.g, L2E coalesces nulls, L2O does not, and different methods are supported). But you can work around that by picking your test data.
Craig Stuntz
This answer do not answer my core question, but it gives me solution I would like to try. Thanks :)
twk