跨多个测试套件的Scalatest共享服务实例

时间:2013-03-27 10:04:47

标签: dependency-injection fixtures scalatest

我有FlatSpec测试类,需要为某些灯具数据使用REST服务。在一次运行所有测试时,我只想实例化REST客户端一次,因为它可能非常昂贵。我怎样才能解决这个问题?当我在IDE中运行时,我是否还可以运行它来运行一个测试类?

2 个答案:

答案 0 :(得分:1)

<强> 1。使用模拟:

当您尝试测试REST服务时,我会建议您使用某种模拟。你可以尝试例如scala-mock。创建模拟服务不是时间/ CPU消耗,因此您可以在所有测试中创建模拟,而不需要共享它们。 看:

trait MyRestService {
  def get(): String
}

class MyOtherService(val myRestService: MyRestService) {
  def addParentheses = s"""(${myRestService.getClass()})"""
}

import org.scalamock.scalatest.MockFactory

class MySpec extends FreeSpec with MockFactory {

  "test1 " in {
    // create mock rest service and define it's behaviour
    val myRestService = mock[MyRestService]
    val myOtherService = new MyOtherService(myRestService)
    inAnyOrder {
      (myRestService.get _).expects().returning("ABC")
    }

    //now it's ready, you can use it
    assert(myOtherService.addParentheses === "(ABC)")
  }
}

<强> 2。或者使用共享装置:

如果您仍想使用REST服务的实际实现并仅创建一个实例,然后使用以下命令与某个测试条件共享:

  • get-fixture methods =&gt;在多次测试中需要相同的可变夹具对象时使用它,之后不需要清理。

  • withFixture(OneArgTest)=&gt;当所有或大多数测试需要相同的灯具时必须清除后才能使用。

有关更多详细信息和代码示例,请参阅http://www.scalatest.org/user_guide/sharing_fixtures#loanFixtureMethods

如果您想与多个套件共享相同的灯具,请使用 org.scalatest.Suites @DoNotDiscover 注释(这些至少需要scalatest-2.0.RC1)< / p>

答案 1 :(得分:0)

Pawel的最后评论很合适。 通过使用BeforaAndAfterAll而不是套件继承套件会更容易。

import com.typesafe.config.ConfigFactory
import com.google.inject.Guice
import org.scalatest.{BeforeAndAfterAll, Suite}
import net.codingwell.scalaguice.InjectorExtensions.ScalaInjector

class EndToEndSuite extends Suite with BeforeAndAfterAll {

    private val injector = {
        val config = ConfigFactory.load
        val module = new AppModule(config) // your module here
        new ScalaInjector(Guice.createInjector(module))
    }

    override def afterAll {
        // your shutdown if needed
    }

    override val nestedSuites = collection.immutable.IndexedSeq(
        injector.instance[YourTest1],
        injector.instance[YourTest2] //...
    )
}
相关问题