簡體   English   中英

使用“in new WithApplication”時如何在specs2中進行設置/拆卸

[英]How to do setup/teardown in specs2 when using “in new WithApplication”

我正在使用帶有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 ")
}

這很好,除了我的所有測試都使用“在新的WithApplication中”。 看來我需要的是一個既是“WithApplication”又是“After”的對象。 下面不編譯,但基本上是我想要的:

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

所以,我的問題是,如何在已經使用“InApplication”的測試中添加setup / teardown? 我主要擔心的是我們所有的測試都使用了這樣的偽路由(所以他們需要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)發生的事情。 為了簡單FakeApplication ,我將從參數列表中刪除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塊很重要,因為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
}

(這可能無法編譯,但你明白了。)

如果你的after方法不需要WithApplication特性中的任何東西,你可以在你的規范中混合AfterExample特征並定義整個規范的after行為:

import org.specs2.specification._

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

  trait SetupAndTeardownPasswordAccount extends WithApplication

  def after = println("cleanup")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM