我的问题和代码基于 Code First Entity Framework Unit Test Examples 博客文章。我正在使用 SQL Compact 4.0,因此我的单元测试是针对实际数据库运行的,使用与博客文章中描述的内容类似的真实数据。
我想在我的生产数据库中使用某些表中的默认值作为种子,但是在运行我的单元测试时我想添加额外的数据并更新一些默认值。
我已经创建了一个自定义的 Initializer 类,它使用默认值为数据库设置种子。对于我的单元测试,我创建了另一个自定义 Initializer,它继承自第一个执行测试特定播种和/或修改的 Initializer:
public class NerdDinnersInitializer : DropCreateDatabaseIfModelChanges<NerdDinners>
{
protected override void Seed(NerdDinners context)
{
var dinners = new List<Dinner>
{
new Dinner()
{
Title = "Dinner with the Queen",
Address = "Buckingham Palace",
EventDate = DateTime.Now,
HostedBy = "Liz and Phil",
Country = "England"
}
};
dinners.ForEach(d => context.Dinners.Add(d));
context.SaveChanges();
}
}
public class NerdDinnersInitializerForTesting : NerdDinnersInitializer
{
protected override void Seed(NerdDinners context)
{
base.Seed(context);
var dinner = context.Dinners.Where(d => d.Country == "England").Single();
dinner.Country = "Ireland";
context.SaveChanges();
}
}
我还为我的单元测试使用了一个基类,它像这样初始化测试数据库:
[TestClass]
public abstract class TestBase
{
protected const string DbFile = "test.sdf";
protected const string Password = "1234567890";
protected NerdDinners DataContext;
[TestInitialize]
public void InitTest()
{
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "",
string.Format("Data Source=\"{0}\";Password={1}", DbFile, Password));
Database.SetInitializer(new NerdDinnersInitializerForTesting());
DataContext = new NerdDinners();
DataContext.Database.Initialize(true);
}
[TestCleanup]
public void CleanupTest()
{
DataContext.Dispose();
if (File.Exists(DbFile))
{
File.Delete(DbFile);
}
}
}
实际的单元测试是这样的:
[TestClass]
public class UnitTest1 : TestBase
{
[TestMethod]
public void TestMethod1()
{
var dinner = new Dinner()
{
Title = "Dinner with Sam",
Address = "Home",
EventDate = DateTime.Now,
HostedBy = "The wife",
Country = "Italy"
};
DataContext.Dinners.Add(dinner);
DataContext.SaveChanges();
var savedDinner = (from d in DataContext.Dinners
where d.DinnerId == dinner.DinnerId
select d).Single();
Assert.AreEqual(dinner.Address, savedDinner.Address);
}
}
当我运行测试时,获取 savedDinner 的 Linq 查询失败,并显示“ObjectContext 实例已被处置,不能再用于需要连接的操作。”异常(exception)。我不知道为什么。
我在这里做的是可以接受的模式吗?任何人都可以阐明为什么这不起作用吗?
谢谢。
最佳答案
今天早上我遇到了类似的问题。问题是由 seed 方法中的 where 子句引起的。一个解决方法(目前)是重写这个:
var dinner = context.Dinners.ToList().Where(d => d.Country == "England").Single();
虽然效率不高(所有对象都从数据库中检索并且过滤将在内存中完成),但它确实解决了我单元测试中的 ObjectDisposedException
。在我的例子中,我只有几个对象,所以我现在可以忍受它。
关于c# - Entity Framework 代码优先 : How to seed a database for unit testing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9907905/