the*_*ski 3 scala playframework specs2
我正在使用带有Scala 2.10.2(运行Java 1.7.0_51)构建的play 2.2.1的Specs2.我一直在阅读有关如何使用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 ")
}
Run Code Online (Sandbox Code Playgroud)
这很好,除了我的所有测试都使用"在新的WithApplication中".看来我需要的是一个既是"WithApplication"又是"After"的对象.下面不编译,但基本上是我想要的:
trait SetupAndTeardownPasswordAccount extends org.specs2.mutable.After with WithApplication
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,如何在已经使用"InApplication"的测试中添加setup/teardown?我主要担心的是我们所有的测试都使用了这样的伪路由(所以他们需要With Application).
val aFakeRequest = FakeRequest(method, url).withHeaders(headers).withBody(jsonBody)
val Some(result) = play.api.test.Helpers.route(aFakeRequest)
result
Run Code Online (Sandbox Code Playgroud)
这是以下代码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))
}
}
Run Code Online (Sandbox Code Playgroud)
实际上很容易修改它以满足您的需求而不会产生许多其他特征.这里缺少的是匿名函数t,您可以在测试中使用它来实现(使用WithApplication).这将是很好做WithApplication一点更强大的能够,如果需要的话之前和之后的测试执行的代码中的任意块.
一种方法可能是创建一个类似的类,WithApplication它接受两个匿名函数,setup并teardown返回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
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
而不是简单地调用匿名函数t,我先打电话setup,然后t,然后teardown.try/finally块很重要,因为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
}
Run Code Online (Sandbox Code Playgroud)
(这可能无法编译,但你明白了.)
| 归档时间: |
|
| 查看次数: |
2821 次 |
| 最近记录: |