mardi 1 septembre 2015

How to initialize fixture once for all tests in scalatest?

According to documentation, fixtures can be passed to tests like this:

def withFixture(test: OneArgTest) = {
    val f = veryLengthyInitialization(test.configMap)
    withFixture(test.toNoArgTest(f))
}

describe("Some test") {
   it("should succeed") { f =>
         f.doSomething()
         // ...
    }
    // many other tests
    // ...
 }

Problem is that the initialization is run for each test, and it takes a very long time, so I would like it to run just once. Documentation suggests an alternative:

  override def beforeAll(configMap: ConfigMap) {
       val fOnce = veryLengthyInitialization(configMap)
       // but how do I pass f to the tests?
       // ugly workaround:
       f = fOnce
 }

 var f: InitType = null

 describe("Some test") {
   it("should succeed") { // hack: no parameter, use var instead
         f.doSomething()
         // ...
    }
    // many other tests
    // ...
 }

It works, but my understanding is that null should be avoided, and it's a bit silly to rely on mutation for something as basic as this. What is the correct way to write such tests?

Aucun commentaire:

Enregistrer un commentaire