0

我正在尝试使用 ScalaTest 和 ScalaCheck 设置基于属性的测试......并且基于输出,我似乎成功了,但它太快了,据我通常理解,ScalaCheck 应该会告诉你测试可能是如何进行的运行,在我的情况下,此信息不存在:

[IJ]sbt:algorithms2_1> testOnly *MedianOf3PartitioningProps
[info] Compiling 1 Scala source to /Users/vasile.gorcinschi/gitPerso/Algorithms/Chapter 2 Sorting/algorithms2_1/target/scala-2.12/test-classes ...
[warn] there was one deprecation warning; re-run with -deprecation for details
[warn] one warning found
[info] Done compiling.

[info] MedianOf3PartitioningProps:
[info] sort
[info] - should sort array of ints from 0 to 100
[info]   +  
[info] ScalaTest
[info] Run completed in 412 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1

这是测试类:

class MedianOf3PartitioningProps extends FlatSpec with Matchers with GeneratorDrivenPropertyChecks with Gens {

  private val medianOf3Partitioning = new MedianOf3Partitioning[Int]

  implicit override val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfig(minSuccessful = 1, maxDiscarded = 500, workers = 1)

  behavior of "sort"

  it should "sort array of ints from 0 to 100" in {
    forAll(arraysGen){  a: Array[Int] =>
      info(s"${a.mkString(",")}")
    medianOf3Partitioning.sort(a) shouldEqual a.sorted }
  }
}

Gens trait 是我的 - 它只包含 Gen[Array[Int]] 的定义:

trait Gens {

  val arraysGen: Gen[Array[Int]] = containerOf[Array, Int](
    chooseNum(Int.MinValue, Int.MaxValue) suchThat { _ < 100 }
  ).suchThat(_.length < 50)
}

将此来源用于测试设置。以防万一,我提供了 scalacheck 和 scalatest 的版本(来自 Dependencies.scala 和 build.sbt):

lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.5"
...
libraryDependencies ++= {
      val scalaTestVersion = "3.0.5"
      val scalaCheckVersion = "1.14.0"
      Seq(scalaTest % Test,
        "org.scalatest" %% "scalatest" % scalaTestVersion % "test",
        "org.scalacheck" %% "scalacheck" % scalaCheckVersion % "test",
        "com.storm-enroute" %% "scalameter" % "0.9"
      )
    }
4

1 回答 1

0

基于 M. Odersky 的“Scala 编程”中的小例子,我从GeneratorDrivenPropertyChecks更一般PropertyChecks的 . 我也发现了我的问题,Gen[Array[Int]]所以我也不得不解决这个问题。发布一个有效的解决方案(发现失败的案例)以防万一这对其他人有帮助:

基因特征:

trait Gens {

  val minIntArraysGen: Gen[Array[Int]] = containerOf[Array, Int](Gen.chooseNum(0, 100))
}

基于属性的测试:

import ca.vgorcinschi.Gens
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
import org.scalatest.prop.PropertyChecks

class MedianOf3PartitioningProps extends WordSpec with PropertyChecks with Gens {

  "sort method" must {
    "sort any Int array" in {
      forAll (minIntArraysGen){ (a: Array[Int]) =>
        whenever(a.nonEmpty) {
          val maybeSorted = new MedianOf3Partitioning[Int].sort(a)
          maybeSorted must equal (a.sorted)
        }
      }
    }
  }
}
于 2019-01-14T11:10:57.447 回答