How to programmatically ignore / skip tests using ScalaTest?

I run some tests using ScalaTest, which rely on connections to test servers. Currently, I have created my own Spec, similar to this one:

abstract class ServerDependingSpec extends FlatSpec with Matchers { def serverIsAvailable: Boolean = { // Check if the server is available } } 

Is it possible to ignore (but not interrupt) tests when this method returns false ?

I am currently doing this in a "hacker" way:

 "Something" should "do something" in { if(serverIsAvailable) { // my test code } } 

but i want something like

 whenServerAvailable "Something" should "do something" in { // test code } 

or

 "Something" should "do something" whenServerAvailable { // test code } 

I think I should define my own tag, but I can only reference the in or ignore source code, and I don’t understand how I should connect my custom implementations.

How to do it?

+7
scala scalatest
source share
3 answers

To achieve this, you can use Tags :

Documentation on how to use tags: http://www.scalatest.org/user_guide/tagging_your_tests

Adding and removing tags with tags with command line parameters: http://www.scalatest.org/user_guide/using_the_runner#specifyingTagsToIncludeAndExclude

Code example :

 import org.scalatest.Tag object ServerIsAvailable extends Tag("biz.neumann.ServerIsAvailable") "Something" should "do something" taggedAs(ServerIsAvailable) in { // your test here } 

Test execution

Running tests is a difficult task. It only works for testOnly and testQuick does not test. In the example, testOnly is short for testOnly *

  sbt "testOnly -- -l biz.neumann.ServerAvailable" 
+9
source share

I would use cancel :

 "Something" should "do something" in { if(!serverIsAvailable) { cancel } // my test code } 

Or simplify it with assume :

 "Something" should "do something" in { assume(serverIsAvailable) // my test code } 
+11
source share

Here are a few tricks to skip the conditional test:

 object WhenServerAvailable extends Tag(if (serverIsAvailable) "" else classOf[Ignore].getName) "Something" should "do something" taggedAs WhenServerAvailable in { ... } 
+2
source share

All Articles