【问题标题】:Dynamicaly Created Tests sbt动态创建测试 sbt
【发布时间】:2021-12-20 13:00:23
【问题描述】:

我正在尝试通过以下方式动态运行一些基本测试(这是我测试的伪代码,我的实际测试要复杂一些):

class ExampleTest extends AnyWordSpec {
  
  def runTests() = {
    for( n <- 1 until 10){
      testNumber(n)
    }
  }
  
  def testNumber(n: Int) = {
    "testNumber" when {
      s"gets the number ${n}" should {
        "fail if the number is different than 0" {
          assert(n == 0)
        }
      }
    }
  }
  
  runTests()
  
}

当我尝试在 IntelliJ 中运行测试时,所有测试都按预期运行。但是当使用sbt tests 时,它说我所有的测试都通过了,即使我的测试没有被实际执行(我收到消息“1 个测试套件已执行。0 个测试在哪里执行”)。 我怎样才能解决这个问题?有没有其他简单的方法可以在 scala 中动态创建测试?)

【问题讨论】:

  • 您可能想要使用 Scalatest forall 功能。例如,请参阅stackoverflow.com/questions/68041007/…
  • 不清楚发生了什么。我用 Java 11、Scala 2.13.6、Sbt 1.4.2 和 Scalatest 3.2.10 和sbt test 成功运行了测试,只用这些测试创建了一个小项目。这可能只是一个错字,但如果您有一些名为 tests 的自定义构建密钥,这可能是您观察到的行为的原因(您要调用的命令是 sbt test)。

标签: scala sbt scalatest


【解决方案1】:

正如评论中提到的,我不确定sbt 的问题是什么。

另一种尝试动态创建测试的方法是使用基于属性的测试。

一种可能的方法是使用表驱动的属性检查,如下例所示(您可以在操作中看到here on Scastie):

import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.prop.TableDrivenPropertyChecks._

class ExampleTest extends AnyWordSpec {

  private val values = Table("n", (1 to 10): _*)

  "testNumber" when {
    forAll(values) { n =>
      s"gets the number ${n}" should {
        "fail if the number is different than 0" in {
          assert(n == 0)
        }
      }
    }
  }

}

当然,所有这些测试都会失败。 ;-)

有关该主题的 ScalaTest 文档的链接:

【讨论】:

    猜你喜欢
    • 2016-02-06
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多