How to programmatically ignore/skip tests with ScalaTest?

 ̄綄美尐妖づ 提交于 2019-11-27 16:17:05

问题


I am running some tests with ScalaTest which rely on connections to test servers to be present. I currently created my own Spec similar to this:

abstract class ServerDependingSpec extends FlatSpec with Matchers {

  def serverIsAvailable: Boolean = {
    // Check if the server is available
  }
}

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

Currently I do it in a "hackish" 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 custom tag, but I can only refer to the source code of in or ignore and I do not understand how I should plug in my custom implementations.

How should I accomplish this?


回答1:


You can use Tags to achieve this:

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

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

Example Code:

import org.scalatest.Tag

object ServerIsAvailable extends Tag("biz.neumann.ServerIsAvailable")

"Something" should "do something" taggedAs(ServerIsAvailable) in { 
  // your test here
}

Running the tests

Running the tests is a bitt tricky. It only works for testOnly and testQuick not test. In the example testOnly is short for testOnly *

 sbt "testOnly -- -l biz.neumann.ServerAvailable"



回答2:


You can use assume:

"Something" should "do something" in {
  assume(serverIsAvailable)

  // my test code
}

You can also use cancel:

"Something" should "do something" in {
  if(!serverIsAvailable) {
    cancel
  }

  // my test code
}



回答3:


Here is some trick to skip a test based on a condition:

object WhenServerAvailable extends Tag(if (serverIsAvailable) "" else classOf[Ignore].getName)

"Something" should "do something" taggedAs WhenServerAvailable in { ... }


来源:https://stackoverflow.com/questions/32460295/how-to-programmatically-ignore-skip-tests-with-scalatest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!