ScalaTest:了解测试执行的顺序

时间:2014-09-12 14:16:15

标签: scala scalatest

我很难理解为什么我的setup-teardown程序在ScalaTest中无法正常工作。基本上,我的测试代码如下所示:

class UserManagerTest extends FlatSpec with ManagerBehaviors[User, UserDAO] {

  "An entity manager" should behave like allFindingManager(UserManager)

  "An entity manager" should behave like countingManager(UserManager)
}


trait ManagerBehaviors[T <: IEntity, D <: AbstractDAO[T]] {

this: FlatSpec =>

   private def withClearDB(entityManager: BasicManager[T, D], testFunction: () => Unit) = {
    try {
      clearDB(entityManager)
      testFunction()
    } finally {
      clearDB(entityManager)
    }
  }

  private def clearDB(manager: BasicManager[T, D]) = {
    manager.all match {
      case Some(entities) => for (entity <- entities) manager.remove(entity.getId)
    }
  }

  def allFindingManager(manager: BasicManager[T, D]) {
    withClearDB(manager,
      () => it should "properly return all elements in the database for the entity" in {

        // Add 10 entities to the database
        for (i <- 1 to 10) manager.persist(manager.defaultEntity)

        manager.all match {
          case Some(entities) => assert(entities.length == 10)
          case None => fail()
        }
      })
  }

  def countingManager(manager: BasicManager[T, D]) {
    withClearDB(manager,
      () => it should "properly count the number of entities managed" in {

        // Add 10 entities to the database
        for (i <- 1 to 10) manager.persist(manager.defaultEntity)

        assert(manager.count == 10)
      })
  }
}

我期望的是以下顺序:

  1. clearDB

  2. allFindingManager

  3. clearDB

  4. clearDB

  5. countingManager

  6. clearDB

  7. 当单独运行时,测试按预期工作 - 数据库在启动时清除,在测试结束时保持空白。

    但是,在运行整个UserManagerTest类时,由于某种原因,它失败并显示以下内容:

    org.scalatest.exceptions.TestFailedException: 20 did not equal 10
    

    这样做的原因是,不管怎样,测试都是在没有间歇性clearDB调用的情况下相互调用的。我对于为什么会发生这种情况一无所知。

    使用调试器并在finally块中放置一个断点时,可能会发现可能发生的事情的线索:这个块确实运行了两次,但这是在BEFORE(!)测试方法之前发生的被执行,这根本没有意义:

    1. clearDB

    2. clearDB

    3. clearDB

    4. clearDB

    5. allFindingManager

    6. countingManager

    7. 任何人都可以帮我解释一下吗?

1 个答案:

答案 0 :(得分:4)

如果你改变了

def countingManager(manager: BasicManager[T, D]) {
  withClearDB(manager,
    () => it should "properly ..." in {

      // Add 10 entities to the database
      for (i <- 1 to 10) manager.persist(manager.defaultEntity)

      assert(manager.count == 10)
    })
}

def countingManager(manager: BasicManager[T, D]) {

  it should "properly ..." in withClearDB(manager,
    () => {
      // Add 10 entities to the database
      for (i <- 1 to 10) manager.persist(manager.defaultEntity)

      assert(manager.count == 10)
    }
  )

}

同样在另一个函数中,执行顺序将如您所愿。