【问题标题】:Entity Framework Integration tests DropCreateDatabaseAlways not clearing database between test实体框架集成测试 DropCreateDatabaseAlways 在测试之间不清除数据库
【发布时间】:2011-12-05 11:37:19
【问题描述】:

我正在编写一组集成测试(使用 MS Test 进行单元测试,测试 Entity Framework 4.2 是否将所有类正确地持久化到数据库中)。

当我一项一项地运行所有测试时,它们都可以正常工作。当我在一个组中运行它们时-其中一些由于返回的对象数量错误而失败-似乎数据库在测试开始时被清理一次,而不是在每次测试之间-即使我可以看到为每个测试创建一个新的上下文,然后处理

有什么想法吗?

public class EmptyDataInitializer : DropCreateDatabaseAlways<myContext>
{
    protected override void Seed(myContext db)
    {
        //Do Nothing Create Empty Database
        db.SaveChanges();
        base.Seed(db);
    }
}

单元/集成测试的精简版

[TestClass]
public class PersistanceTests
{
    //Creating two instances of our Repository so that we can make sure that we are reading from our database rather than in-memory
    private myContext _db;
    private myContext _dbResults;
    private readonly ISettings _configSettings;

    public PersistanceTests()
    {
        _configSettings = MockRepository.GenerateStub<ISettings>();
        _configSettings.ConnectionString = "data source=.;initial catalog=myContext_Test; Integrated Security=SSPI; Pooling=false";

        Database.SetInitializer(new EmptyDataInitializer());
    }

    //This is called a single time after the last test has finished executing
    [TestCleanup]
    public void TearDownTest()
    {
       _db.Dispose();
        _db = null;
       _dbResults.Dispose();
        _dbResults = null;
    }

    //This is called each time prior to a test being run

    [TestInitialize]
    public void SetupTest()
    {          
        _db = new myContext(_configSettings);
        _dbResults = new myContext(_configSettings);

        // This forces the database to initialise at this point with the initialization data / Empty DB
        var count = _db.Accounts.Count();
        var resultCount = _dbResults.Accounts.Count();
        if (count != resultCount) throw new InvalidOperationException("We do not have a consistant DB experiance.");
    }
    [TestMethod]
    public void OrganisationPersistanceTest()
    {
        // Arrange
        var apple = new Organisation { Name = "Apple" };
        _db.Organisations.Add(apple);
        // Act
        _db.SaveChanges();
        var organisationsCount = _dbResults.Organisations.Count();
        var organisationsAppleCount = _dbResults.Organisations.Where(a => a.Id == apple.Id).Count();
        var result = _dbResults.Organisations.FirstOrDefault(a => a.Id == apple.Id);
        // Assert
        Assert.IsTrue(organisationsCount == 1, string.Format("Organisations Count Mismatch -  Actual={0}, Expected={1}", organisationsCount, 1));
        Assert.IsTrue(organisationsAppleCount == 1, string.Format("Apple Organisations Count Mismatch -  Actual={0}, Expected={1}", organisationsAppleCount, 1));
        Assert.IsNotNull(result, "Organisations Result should not be null");
        Assert.AreEqual(result.Name, apple.Name, "Name Mismatch");
    }

    //A Unit test
    [TestMethod]
    public void OrganisationWithNumberOfPeople_PersistanceTest()
    {
        // Arrange
        var person = new Person { Firstname = "Bea" };
        var anotherPerson = new Person { Firstname = "Tapiwa" };
        var apple = new Organisation { Name = "Apple" };
        apple.AddPerson(person);
        apple.AddPerson(anotherPerson);
        _db.Organisations.Add(apple);
        // Act
        _db.SaveChanges();
        var organisationsCount = _dbResults.Organisations.Count();
        var organisationsAppleCount = _dbResults.Organisations.Where(a => a.Id == apple.Id).Count();
        var result = _dbResults.Organisations.FirstOrDefault(a => a.Id == apple.Id);
        var peopleCountInOrganisation = result.People.Count();
        // Assert
        Assert.IsTrue(organisationsCount == 1, string.Format("Organisations Count Mismatch -  Actual={0}, Expected={1}", organisationsCount, 1));
        Assert.IsTrue(organisationsAppleCount == 1, string.Format("Apple Organisations Count Mismatch -  Actual={0}, Expected={1}", organisationsAppleCount, 1));
        Assert.IsNotNull(result, "Organisations Result should not be null");
        Assert.AreEqual(result.People.Count, peopleCountInOrganisation, "People count mismatch in organisation Apple - Actual={0}, Expected={1}", peopleCountInOrganisation, 2); 
        Assert.AreEqual(result.Name, apple.Name, "Name Mismatch");
   }

}

通过测试,我可以看到 SetupTest 和 TearDownTest 方法被调用,但它似乎没有在测试之间清理数据库。

【问题讨论】:

  • 好吧,Dokey,它似乎是一个答案(尽管对我来说似乎有点骇人听闻)是修改 TestCleanup 方法,以便它在每次测试后显式删除并重新创建数据库 [TestCleanup] public void TearDownTest() { if (_db.Database.Exists()) { _db.Database.Delete(); _db.Database.CreateIfNotExists(); _db.Dispose(); _db = null; _dbResults.Dispose(); _dbResults = null; }
  • 好吧,甚至更好的答案 - 添加一个数据库。初始化(强制:真);进入 TestInitialize 方法。 [TestInitialize] public void SetupTest() { _db = new myContext(_configSettings); _db.Database.Initialize(force: true);

标签: unit-testing entity-framework-4.1


【解决方案1】:

好的,甚至更好的答案 - 添加一个数据库。初始化(强制:真); 进入 TestInitialize 方法。

[TestInitialize]
public void SetupTest()
{          
    _db = new myContext(_configSettings);
    _db.Database.Initialize(force: true);
    _dbResults = new myContext(_configSettings);

    // This forces the database to initialise at this point with the initialization data / Empty DB
    var count = _db.Accounts.Count();
    var resultCount = _dbResults.Accounts.Count();
    if (count != resultCount) throw new InvalidOperationException("We do not have a consistant DB experiance.");
}

【讨论】:

  • 这适用于常规连接(非 MDF),您是否有提示为什么当连接字符串包含 AttachDBFilename 参数时相同的代码不起作用?在调用.Initialize(true) 之后,EntityFramework 确实删除了指定路径中的 .MDF 文件,但抛出了一个 SQL 异常,抱怨找不到 .MDF 文件!这与我留下的一些恢复标志/选项有关吗?这对我来说似乎是一种非常随机的行为!
【解决方案2】:

我使用助手来执行此类任务:

public abstract class TestingHelper
{
        public static void ClearDatabase()
        {
            DatabaseContext myDbContext = new DatabaseContext();
            myDbContext.Database.Delete();
            myDbContext.Database.Create();
            //FillDatabase(lawyers); //<- OPTIONAL if you want to add rows to any type tables
        }
}

然后在你的测试设置中使用它:

[SetUp]
public void MyTests_SetUp()
{
      TestingHelper.ClearDatabase();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-03
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多