【问题标题】:How to use Specs2 with Scalacheck to automate testing of String arguments?如何使用 Specs2 和 Scalacheck 自动测试字符串参数?
【发布时间】:2011-09-09 22:10:59
【问题描述】:

为 Scala 重写的 specs2 测试框架将自动化测试与 scalacheck 集成在一起。 specs2 文档中给出的示例是关于如何将 scalacheck 与 specs2 一起使用 use integers 或更复杂的自定义生成器,如 eric's json example

虽然试图让一个稍微不那么复杂的示例工作,但我很挣扎,因为如果我想生成字符串参数而不是整数,我不知道如何使用 specs2 和 scalacheck。这个快速入门示例如何


import org.scalacheck._

object StringSpecification extends Properties("String") { property("startsWith") = Prop.forAll((a: String, b: String) => (a+b).startsWith(a))

property("endsWith") = Prop.forAll((a: String, b: String) => (a+b).endsWith(b))

// Is this really always true? property("concat") = Prop.forAll((a: String, b: String) => (a+b).length > a.length && (a+b).length > b.length )

property("substring") = Prop.forAll((a: String, b: String) => (a+b).substring(a.length) == b )

property("substring") = Prop.forAll((a: String, b: String, c: String) => (a+b+c).substring(a.length, a.length+b.length) == b ) }

scalacheck homepage 看,如果它是使用 scalacheck 集成编写为 Specs2 规范?

【问题讨论】:

    标签: scala specs scalacheck specs2


    【解决方案1】:

    一个非常直接的翻译是使用check方法和简单的函数:

    package test
    
    import org.specs2._
    import org.scalacheck._
    
    class ScalaCheckExamples extends Specification with ScalaCheck { def is =
    
      "startsWith" ! check { (a: String, b: String) => (a+b).startsWith(a) }                                                ^
      "endsWith"   ! check { (a: String, b: String) => (a+b).endsWith(b) }                                                  ^
      "concat"     ! check { (a: String, b: String) => (a+b).length > a.length && (a+b).length > b.length }                 ^
      "substring"  ! check { (a: String, b: String) => (a+b).substring(a.length) == b }                                     ^
      "substring"  ! check { (a: String, b: String, c: String) => (a+b+c).substring(a.length, a.length+b.length) == b }     ^
                                                                                                                            end
     }
    

    而输出实际上显示concat属性不正确:

      [info] + startsWith
      [info] + endsWith
      [error] x concat
      [error]   A counter-example is ['', ''] (after 0 try)
      [error] the value is false
      [error]  (ScalaCheckExamplesSpec.scala:6)
      [info] + substring
      [info] + substring
      [info]
      [info] Total for specification ScalaCheckExamplesSpec
      [info] Finished in 7 seconds, 547 ms
      [info] 5 examples, 401 expectations, 1 failure, 0 error
      [info]
    

    埃里克。

    【讨论】:

    • 感谢您的回答。这确实为我澄清了一些事情。也许您想考虑将此示例添加到示例代码树中?
    【解决方案2】:

    有关在 specs2 中使用 ScalaCheck 库的更多信息,请查看ScalaCheck Guide in the specs2 documentation

    【讨论】:

    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多