gpt4 book ai didi

scala - 使用 "in new WithApplication"时如何在 specs2 中进行设置/拆卸

转载 作者:行者123 更新时间:2023-12-04 15:54:44 24 4
gpt4 key购买 nike

我正在使用 Specs2 和使用 Scala 2.10.2(运行 Java 1.7.0_51)构建的 play 2.2.1。我一直在阅读有关如何使用 Specs2 进行设置/拆卸的信息。我已经看到使用“After”特征的示例如下:

class Specs2Play extends org.specs2.mutable.Specification {
"this is the first example" in new SetupAndTeardownPasswordAccount {
println("testing")
}
}

trait SetupAndTeardownPasswordAccount extends org.specs2.mutable.After {
println("setup")

def after = println("teardown ")
}

这很好用,除了我所有的测试都使用“in new WithApplication”。看来我需要的是拥有一个既是“WithApplication”又是“After”的对象。下面没有编译,但本质上是我想要的:

trait SetupAndTeardownPasswordAccount extends org.specs2.mutable.After with WithApplication

所以,我的问题是,如何将设置/拆卸添加到已经在使用“in WithApplication”的测试中?我主要担心的是我们所有的测试都使用了这样的假路由(所以他们需要 With Application)。

val aFakeRequest = FakeRequest(method, url).withHeaders(headers).withBody(jsonBody)
val Some(result) = play.api.test.Helpers.route(aFakeRequest)
result

最佳答案

这是WithApplication的代码:

abstract class WithApplication(val app: FakeApplication = FakeApplication()) extends Around with Scope {
implicit def implicitApp = app
override def around[T: AsResult](t: => T): Result = {
Helpers.running(app)(AsResult.effectively(t))
}
}

实际上很容易修改它以满足您的需求,而无需创建一堆其他特征。这里缺少的部分是匿名函数 t,您可以在测试中为其提供实现(使用 WithApplication)。如果有必要,最好使 WithApplication 更加健壮,以便能够在测试之前和之后执行任意代码块。

一种方法可以是创建一个类似于 WithApplication 的类,它接受两个匿名函数 setupteardown 都返回 Unit 。我真正需要做的就是修改 AsResult.effectively(t) 中发生的事情。为了简单起见,我将从参数列表中删除 app 参数,并始终使用 FakeApplication。您似乎没有提供不同的配置,并且可以随时添加回来。

abstract class WithEnv(setup: => Unit, teardown: => Unit) extends Around with Scope {
implicit def implicitApp = app
override def around[T: AsResult](t: => T): Result = {
Helpers.running(app)(AsResult.effectively{
setup
try {
t
} finally {
teardown
}
})
}
}

我不是简单地调用匿名函数t,而是先调用setup,然后调用t,再调用teardown . try/finally block 很重要,因为 specs2 中失败的测试会抛出异常,我们希望确保无论结果如何,都会执行 teardown

现在您可以使用函数轻松设置测试环境。

import java.nio.files.{Files, Paths}

def createFolder: Unit = Files.createDirectories(Paths.get("temp/test"))

def deleteFolder: Unit = Files.delete("temp/test")

"check if a file exists" in new WithEnv(createFolder, deleteFolder) {
Files.exists(Paths.get("temp/test")) must beTrue
}

(这可能无法编译,但你明白了。)

关于scala - 使用 "in new WithApplication"时如何在 specs2 中进行设置/拆卸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239165/

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