|
| 1 | +package com.baeldung.scala.conditionaltests |
| 2 | + |
| 3 | +import org.scalatest.{Assertion, Ignore, Tag} |
| 4 | +import org.scalatest.wordspec.AnyWordSpec |
| 5 | + |
| 6 | +object ServiceChecker { |
| 7 | + def isServiceAvailable: Boolean = false |
| 8 | +} |
| 9 | + |
| 10 | +object RequiresAvailableService extends Tag("RequiresAvailableService") |
| 11 | +object RequiresAvailableServiceConditional |
| 12 | + extends Tag( |
| 13 | + if (ServiceChecker.isServiceAvailable) "" else classOf[Ignore].getName |
| 14 | + ) |
| 15 | + |
| 16 | +object AlwaysIgnoreTest extends Tag("org.scalatest.Ignore") |
| 17 | + |
| 18 | +class ConditionalUnitTest extends AnyWordSpec { |
| 19 | + |
| 20 | + private def skipTestIfServerUnavailable(test: => Assertion): Assertion = { |
| 21 | + if (ServiceChecker.isServiceAvailable) { |
| 22 | + test |
| 23 | + } else cancel("Not executing test since the service is not available") |
| 24 | + } |
| 25 | + |
| 26 | + "Conditional Tests" should { |
| 27 | + "run this test only if the service is available by checking tag" taggedAs (RequiresAvailableService) in { |
| 28 | + succeed |
| 29 | + } |
| 30 | + |
| 31 | + "run this test anyways" in { |
| 32 | + succeed |
| 33 | + } |
| 34 | + |
| 35 | + "run this test using the conditional if-else tag if service is available" taggedAs (RequiresAvailableServiceConditional) in { |
| 36 | + succeed |
| 37 | + } |
| 38 | + |
| 39 | + "run this test using simple if-else condition" in { |
| 40 | + if (!ServiceChecker.isServiceAvailable) { |
| 41 | + cancel("excluding this test due to service not available") |
| 42 | + } |
| 43 | + succeed |
| 44 | + } |
| 45 | + |
| 46 | + "run this test based on assume" in { |
| 47 | + assume(ServiceChecker.isServiceAvailable) |
| 48 | + succeed |
| 49 | + } |
| 50 | + |
| 51 | + "run this test using skipTestIfServerUnavailable method" in skipTestIfServerUnavailable { |
| 52 | + succeed |
| 53 | + } |
| 54 | + |
| 55 | + "always ignore this test since Ignore name is used in Tag" taggedAs (AlwaysIgnoreTest) in { |
| 56 | + fail("this fails, but it should never reaches here due to the tag") |
| 57 | + } |
| 58 | + |
| 59 | + "ignore this test using the ignore keyword conditionally" ignore { |
| 60 | + fail() |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments