如何减少ScalaCheck生成的测试用例的数量? [英] How can I reduce the number of test cases ScalaCheck generates?

查看:129
本文介绍了如何减少ScalaCheck生成的测试用例的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决两个ScalaCheck(+ specs2)问题:

I'm trying to solve two ScalaCheck (+ specs2) problems:

  1. 是否可以更改ScalaCheck生成的案例数量?

  1. Is there any way to change the number of cases that ScalaCheck generates?

如何生成包含某些Unicode字符的字符串?

How can I generate strings that contain some Unicode characters?

例如,我想生成大约10个包含字母数字和Unicode字符的随机字符串.但是,此代码始终生成100个随机字符串,并且它们严格基于字母字符:

For example, I'd like to generate about 10 random strings that include both alphanumeric and Unicode characters. This code, however, always generates 100 random strings, and they are strictly alpha character based:

"make a random string" in {
    def stringGenerator = Gen.alphaStr.suchThat(_.length < 40)
    implicit def randomString: Arbitrary[String] = Arbitrary(stringGenerator)

    "the string" ! prop { (s: String) => (s.length > 20 && s.length < 40) ==> { println(s); success; } }.setArbitrary(randomString)
}

修改

我刚刚意识到还有另一个问题:

I just realized there's another problem:

  1. ScalaCheck通常会放弃而不生成100个测试用例

当然,我不想100,但是显然我的代码正在尝试生成一组过于复杂的规则.上次运行时,我看到经过47次测试后放弃了."

Granted I don't want 100, but apparently my code is trying to generate an overly complex set of rules. The last time it ran, I saw "gave up after 47 tests."

推荐答案

"47次测试后放弃"错误表示您的条件(包括suchThat谓词和==>部分)都过于严格.幸运的是,将它们烘烤到生成器中通常并不难,并且您可以编写类似的代码(这也解决了选择任意字符,而不仅仅是字母数字字符的问题):

The "gave up after 47 tests" error means that your conditions (which include both the suchThat predicate and the ==> part) are too restrictive. Fortunately it's often not too hard to bake these into your generator, and in your case you can write something like this (which also addresses the issue of picking arbitrary characters, not just alphanumeric ones):

val stringGen: Gen[String] = Gen.chooseNum(21, 40).flatMap { n =>
  Gen.buildableOfN[String, Char](n, arbitrary[Char])
}

在这里,我们选择一个在所需范围内的任意长度,然后选择该数量的任意字符,并将它们连接成一个字符串.

Here we pick an arbitrary length in the desired range and then pick that number of arbitrary characters and concatenate them into a string.

您还可以增加maxDiscardRatio参数:

import org.specs2.scalacheck.Parameters
implicit val params: Parameters = Parameters(maxDiscardRatio = 1024)

但这通常不是一个好主意-如果您舍弃大多数生成的值,则测试将花费更长的时间,并且重构生成器通常会更清洁,更快.

But that's typically not a good idea—if you're throwing away most of your generated values your tests will take longer, and refactoring your generator is generally a lot cleaner and faster.

您还可以通过设置适当的参数来减少测试用例的数量:

You can also decrease the number of test cases by setting the appropriate parameter:

implicit val params: Parameters = Parameters(minTestsOk = 10)

但是,再次提醒您,除非您有充分的理由这样做,否则建议您信任默认值.

But again, unless you have a good reason to do this, I'd suggest trusting the defaults.

这篇关于如何减少ScalaCheck生成的测试用例的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆