gpt4 book ai didi

scala - 在 playframework 假应用程序中快速执行测试

转载 作者:行者123 更新时间:2023-12-03 03:58:59 25 4
gpt4 key购买 nike

按照描述运行测试 here

"Spec" should {
"example" in new WithApplication {
...
}
}

对我来说慢得令人难以接受。这是因为新的 WithApplication 在每个示例中都会启动和停止框架。不要误会我的意思,框架本身加载速度非常快,但是如果配置了数据库(惊讶!),情况就会变得很糟糕。

以下是一些测量结果:

"The database layer" should {

"test1" in {
1 must be equalTo(1)
}
...
"test20" in {
1 must be equalTo(1)
}
}

执行时间:2秒。每个示例中使用 WithApplication 进行的相同测试耗时 9 秒

感谢this answer,我能够取得更好的结果

import play.api.Play
import play.api.test.FakeApplication
import org.specs2.mutable.Specification
import scalikejdbc._

class MySpec extends Specification {

var fake: FakeApplication = _

step {fake = FakeApplication(...)}
step {Play.start(fake)}

"The database layer" should {

"some db test" in {
DB localTx { implicit session =>
...
}
}

"another db test" in {
DB localTx { implicit session =>
...
}
}

step {Play.stop()}
}

}

优点:性能提升

缺点:

  • 需要复制粘贴设置和拆卸代码,因为不知道如何重用它(我所说的重用是指“class MySpec extends规范NoWasteOfTime

  • new WithApplication() 调用 Helpers.running,如下所示

synchronized {
try {
Play.start(fakeApp)
block
} finally {
Play.stop()
play.api.libs.ws.WS.resetClient()
}
}

因此,如果没有反射,我无法完全模拟 Helpers.running 行为(resetClient 对于我的代码不可见)。

请建议如何打破缺点或使用不同的方法来解决我的问题。

最佳答案

我不知道这是否是最好的解决方案,但在这个线程中: Execute code before and after specification

您可以阅读可重用代码的解决方案。我几乎没有修改就实现了它。对我来说,beforeAll 步骤没有运行并添加了 sequential 修饰符。

import org.specs2.mutable._
import org.specs2.specification._

class PlayAppSpec extends Specification with BeforeAllAfterAll{
sequential
lazy val app : FakeApplication = {
FakeApplication()
}

def beforeAll(){
Play.start(app)
}

def afterAll(){
Play.stop()
}
}
import org.specs2.specification.Step

trait BeforeAllAfterAll extends Specification {
// see specs2 User Guide, linked below
override def map(fragments: =>Fragments) = {
beforeAll()
fragments ^ Step(afterAll)
}


def beforeAll()
def afterAll()
}

我认为map使用Step(...)^fragments^Step(...)会更好,但它没有为我运行beforeAll。 user guide在“全局设置/拆卸”中表示使用惰性值。

总的来说,设置这个很痛苦。我的问题是线程“Thread-145”中出现异常 java.net.SocketException:连接重置或者

配置错误[无法连接到数据库[默认]] (Configuration.scala:559)

当重复使用同一个 FakeApplication 时:SQLException:尝试从已关闭的池中获取连接。

我认为这种方式比总是为每个“in” block 创建一个新应用程序或将所有测试添加到一个 block 中更合乎逻辑。

关于scala - 在 playframework 假应用程序中快速执行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20254705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com