我有一个代码首先使用EF代码,我想在我的单元测试中进行单元测试我想在测试开始时使用一个真正的空数据库,所以我做了:
[TestInitialize]
public void Initialize()
{
Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
}
[TestCleanup]
public void CleanUp()
{
MyContext db = new MyContext();
db.Database.Delete();
}
但由于测试并行运行,这不起作用,所以我用我的测试进行了订单测试
有问题,因为数据库有时不会因为正在使用而被删除…
有人有更好的策略吗?我想也许每个测试都会创建自己的数据库?如果这是个好主意我怎么能实现这个目标?
最佳答案 请试试这个
[TestClass]
public class UnitTestClass
{
private static string testConnString;
[TestInitialize]
public void Initialize()
{
testConnString = GetTestConnString();
using (MyContext db = new MyContext(testConnString, new DropCreateDatabaseAlways<MyContext>()))
{
db.UnderlyingContext.Connection.Open();
}
}
[TestMethod]
public void TestMethod1()
{
}
[TestCleanup]
public void CleanUp()
{
using (MyContext db = new MyContext(testConnString))
{
db.Database.Delete();
}
}
private static string GetTestConnString()
{
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
csb.DataSource = @"MYPC\SQLEXPRESS"; // Replace it with your SQL-server name
csb.InitialCatalog = "DB"+Guid.NewGuid().ToString().Replace("-","");
csb.IntegratedSecurity = true;
return csb.ToString();
}
}
public class MyContext : DbContext
{
private static IDatabaseInitializer<MyContext> _Initializer;
public MyContext(string connString, IDatabaseInitializer<MyContext> initializer = null)
: base(connString)
{
_Initializer = initializer;
}
public ObjectContext UnderlyingContext
{
get { return (this as IObjectContextAdapter).ObjectContext; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (_Initializer != null)
{
Database.SetInitializer(_Initializer);
}
base.OnModelCreating(modelBuilder);
}
}