2012-06-07 41 views
7

我想用specs2在scala中測試一些數據庫相關的東西。目標是測試「db運行」,然後執行測試。我發現如果數據庫關閉,我可以使用Matcher類中的orSkip。如何在沒有匹配器的情況下跳過specs2中的測試?

問題是,我得到了一個匹配條件的輸出(如PASSED),並且該示例被標記爲SKIPPED。我想要的只是:如果測試數據庫處於脫機狀態,只執行一個標記爲「SKIPPED」的測試。這裏是我的 「TestKit」

package net.mycode.testkit 

import org.specs2.mutable._ 
import net.mycode.{DB} 


trait MyTestKit { 

    this: SpecificationWithJUnit => 

    def debug = false 

    // Before example 
    step { 
    // Do something before 
    } 

    // Skip the example if DB is offline 
    def checkDbIsRunning = DB.isRunning() must be_==(true).orSkip 

    // After example 
    step { 
    // Do something after spec 
    } 
} 

的代碼,並在這裏爲我的規格代碼:現在

package net.mycode 

import org.specs2.mutable._ 
import net.mycode.testkit.{TestKit} 
import org.junit.runner.RunWith 
import org.specs2.runner.JUnitRunner 

@RunWith(classOf[JUnitRunner]) 
class MyClassSpec extends SpecificationWithJUnit with TestKit with Logging { 

    "MyClass" should { 
    "do something" in { 
     val sut = new MyClass() 
     sut.doIt must_== "OK" 
    } 

    "do something with db" in { 
    checkDbIsRunning 

    // Check only if db is running, SKIP id not 
    } 
} 

輸出:我想這是

Test MyClass should::do something(net.mycode.MyClassSpec) PASSED 
Test MyClass should::do something with db(net.mycode.MyClassSpec) SKIPPED 
Test MyClass should::do something with db(net.mycode.MyClassSpec) PASSED 

輸出:

Test MyClass should::do something(net.mycode.MyClassSpec) PASSED 
Test MyClass should::do something with db(net.mycode.MyClassSpec) SKIPPED 
+1

你可以舉一個例子,說明當前的控制檯輸出是什麼,以及期望的輸出是什麼? – Eric

+0

添加輸出樣本 – Alebon

回答

6

我想你可以使用一個簡單的條件做你想要什麼:

class MyClassSpec extends SpecificationWithJUnit with TestKit with Logging { 

    "MyClass" should { 
    "do something" in { 
     val sut = new MyClass() 
     sut.doIt must_== "OK" 
    } 
    if (DB.isRunning) { 
     // add examples here 
     "do something with db" in { ok } 
    } else skipped("db is not running") 
    } 
} 
+0

它並不完美,但非常有幫助;) – Alebon

+0

@Eric當運行test.functionality.Login:org.specs2.execute.SkipException時,會引發異常 - 未捕獲的異常。有沒有一種方法,這不會拋出異常? – 0fnt

+1

我認爲''db沒有運行「跳過'而應該工作。 – Eric

5

您是否嘗試過使用args(skipAll=true)的說法?查看few examples here

不幸的是(據我所知),你不能跳過單元​​規範中的一個例子。你可以,但是,跳過規格結構用這樣的說法是這樣,那麼你可能需要創建單獨的規範:

class MyClassSpec extends SpecificationWithJUnit { 

    args(skipAll = false) 

    "MyClass" should { 
    "do something" in { 
     success 
    } 

    "do something with db" in { 
     success 
    } 
    } 
} 
+0

順便說一句,你不需要@RunWith從WithJUnit繼承時 – OlegYch

+0

沒錯,解決了這個問題。順便說一下,我正在研究[GSoC 2012期間Scala IDE集成Specs2](http://xcafebabe.blogspot.hu/2012/06/first-thoughts-on-scala.html),希望我們能夠在夏季結束時運行它沒有任何註釋:-) – rlegendi

+3

有一個專門的快捷方式,['skipAllIf'](http://etorreborre.github.com/specs2/guide/org.specs2.guide.Structure.html #跳過+例子)來跳過所有的例子,如果條件滿足。此方法更短,並且如果您的布爾表達式拋出任何錯誤,它將捕獲異常。 – Eric

相關問題