使用Scalacheck与Inside trait

时间:2018-05-31 02:51:07

标签: scala scalatest scalacheck

我有一个非常简单的场景:测试任何一对长度为10的随机字符串作为参数传递给案例类对(一个正在测试的自定义字符串)应该是相同的。

class ExercisesPropSpec extends PropSpec with Checkers with Matchers with Inside{

  import Exercises._

  lazy val genPairs = for {
    left <- Gen.listOfN(10, Gen.alphaChar)
    right <- Gen.listOfN(10, Gen.alphaChar)
  } yield (left.mkString, right.mkString)

  property("pattern match tuples of alphanumerics to our custom pair class"){
    forAll(genPairs) {case (left: String, right: String) =>
      val pair = Pair(left, right)
      inside(pair) { case Pair(firstName, lastName) =>
        firstName shouldEqual(left)
        lastName shouldEqual(right)
      }
    }
  }
}

但是,当我从sbt运行testOnly *ExercisesPropSpec时,我收到此编译错误:

Compiling 1 Scala source to /home/vgorcinschi/ideaProjects/Learning Concurrent Programming in Scala/chapter01_introduction/target/scala-2.12/test-classes ...
[error] ~/ideaProjects/Learning Concurrent Programming in Scala/chapter01_introduction/src/test/scala/org/learningconcurrency/ExercisesPropSpec.scala:18:28: No implicit view available from org.scalatest.Assertion => org.scalacheck.Prop.
[error]     check(forAll(genPairs) {case (left: String, right: String) =>
[error]                            ^

A note在scalacheck-cookbook sais中

  

错误消息表明我们的属性检查不是   根据布尔逻辑进行评估

我希望最后的内部块应该返回布尔值。如果您能够指出我对基于属性的测试的理解或在此实现中使用Inside trait而遗漏了什么,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

你只需要写

firstName == left && lastName == right

代替。

(如果shouldEqual确实返回Boolean,则firstName shouldEqual(left)的结果将被丢弃。)