关于scalaTest中“beforeAll”这样的方法的有用性,我有更多的哲学困惑。我一直在寻找一个答案,为什么需要像beforeAll这样的结构?我确实理解为什么这个设计决定是有原因的,但却不能仔细考虑。有人能帮上忙吗?
例如根据在线教程所建议的方式,
class TestExample extends FunSuite with BeforeAndAfterAll {
private var _tempDir: File = _
protected def tempDir: File = _tempDir
override def beforeAll(): Unit = {
super.beforeAll()
_tempDir = Utils.createTempDir(namePrefix = this.getClass.getName)
}
test("...") {
// using the variable in the function
}
} vs
class TestExample extends FunSuite with BeforeAndAfterAll {
private val tempDir: File = Utils.createTempDir(namePrefix =
this.getClass.getName)
}
test("...") {
// Use the initialized variable here.
} 发布于 2016-02-22 04:52:25
如果你要在afterAll中进行清理,我认为在beforeAll中进行设置是对称的。另外,如果你需要做一些不涉及初始化实例变量的副作用,可以使用beforeAll。但是,在您给出的示例中,您在afterAll中不需要做任何清理工作,而在所有测试之前所做的只是初始化实例变量,我将使用普通的老式初始化。
val初始化器和beforeAll之间的另一个区别是val初始化器在类被实例化时发生,而beforeAll在实例执行时发生。如果你想延迟初始化直到类运行,你可以使用惰性函数。
https://stackoverflow.com/questions/35527660
复制相似问题