2013-11-03 76 views
1

我想在Scala中使用specs2運行一些測試,但我有一些測試用例沒有執行的問題。斯卡拉specs2與上下文嵌套

這是舉例說明我的問題的最小例子。

BaseSpec.scala

package foo 

import org.specs2.mutable._ 

trait BaseSpec extends Specification { 
    println("global init") 
    trait BeforeAfterScope extends BeforeAfter { 
    def before = println("before") 
    def after = println("after") 
    } 
} 

FooSpec.scala

package foo 

import org.specs2.mutable._ 

class FooSpec extends BaseSpec { 
    "foo" should { 
    "run specs" in new BeforeAfterScope { 
     "should fail" in { 
     true must beFalse 
     } 
    } 
    } 
} 

我希望測試失敗,但它似乎案「發生故障」中的嵌套in說法沒有得到執行。

如果我刪除嵌套的in語句或​​,測試行爲正確,所以我想我錯過了一些東西,但我沒有設法在文檔中找到它。

[編輯]

在我的使用情況下,我目前填充在before方法數據庫,並清除它在after方法。但是,我希望能夠有幾個測試用例,而不需要在每個測試用例之間重新清理並填充數據庫。 什麼是正確的方法來做到這一點?

回答

9

範圍必須完全建立在其中創建您的例子:

class FooSpec extends BaseSpec { 
    "foo" should { 
    "run specs" in { 
     "should fail" in new BeforeAfterScope { 
     true must beFalse 
     } 
    } 
    } 
} 

[更新:2015年10月12日爲specs2 3.X]

請注意,如果你不這樣做需要繼承​​特徵的值,實際上BaseSpec擴展爲org.specs2.specification.BeforeAfterEach並且在那裏定義beforeafter方法實際上更簡單。

另一方面,如果你想在你的所有例子之前和之後做一些設置/拆卸,你需要BeforeAfterAll特質。以下是使用這兩種特性的規格:

import org.specs2.specification.{BeforeAfterAll, BeforeAfterEach} 

trait BaseSpec extends Specification with BeforeAfterAll with BeforeAfterEach { 
    def beforeAll = println("before all examples") 
    def afterAll = println("after all examples") 

    def before = println("before each example") 
    def after = println("after each example") 
} 

class FooSpec extends BaseSpec { 
    "foo" should { 
    "run specs" in { 
     "should fail" in { 
     true must beFalse 
     } 
    } 
    } 
} 

該方法記錄在here

+0

謝謝你的回答。我剛剛編輯了我的問題來解釋我正在嘗試做什麼。 –

+0

我明白了!非常感謝您的幫助。 –

+0

@Eric鏈接被破壞 –