使用内存中的SQLite测试基于EF SQL Server的应用程序? [英] Testing EF SQL Server based application with in-memory SQLite?
问题描述
我正在将SQL Server与Entity Framework一起用于通过VS2010 RC在.NET 4中开发Web应用程序。我想使用示例数据准备测试数据库。
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.
我应该准备真实数据库的副本(例如另一个SQL Server数据库)进行测试,还是可以使用SQLite
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?
如果使用SQLite,是否可以使用EF为SQL Server数据库创建的相同模型?如何将架构从SQL Server迁移到内存中的SQLite?
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?
如何测试将EF与SQL Server一起使用的代码?
How are you testing your code that uses EF with SQL Server?
感谢共享。
推荐答案
我对对象和DI使用LINQ。
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;
}
}
现在我可以使用构造函数注入来注入模拟存储库供测试用。通常,您将为此使用DI框架。但是重要的是,模拟存储库可以使用LINQ来对象:
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();
}
}
现在我可以测试:
[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);
}
这篇关于使用内存中的SQLite测试基于EF SQL Server的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!