2012-06-07 30 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

相关问题