首页 > 解决方案 > 使用 Randoop 生成测试用例(基于前置条件和后置条件)

问题描述

我正在尝试使用 Randoop(通过遵循Randoop Manual)根据存储在 JSON 文件中的前置条件和后置条件规范生成测试用例。

目标程序是以下(错误的)Java 方法。

package com.example.math;

public class Math {
    /*Expected Behavior:
          Given upperBound >= 0, the method returns
               1 + 2 + ... + upperBound                 
      But This method is buggy and works only on
      inputs with odd value, e.g. for upperBound == 4,
      the method returns 1 + 2 + 3 + 4 + 1 instead of
      1 + 2 + 3 + 4                                   */
    public static int sum(int upperBound) {
        int s = 0;
        for (int i = 0; i <= upperBound; i++) {
            s += i;
        }
        if (upperBound % 2 == 0) {// <--------- BUG!
            s++;                  // <--------- BUG!
        }                         // <--------- BUG!
        return s;
    }
}

我使用以下 JSON 文件来指定方法的所需行为:

[
  {
    "operation": {
      "classname": "com.example.math.Math",
      "name": "sum",
      "parameterTypes": [ "int" ]
    },
    "identifiers": {
      "parameters": [ "upperBound" ],
      "returnName": "res"
    },
    "post": [
      {
        "property": {
          "condition": "res == upperBound * (upperBound + 1) / 2",
          "description": ""
        },
        "description": "",
        "guard": {
          "condition": "true",
          "description": ""
        }
      }
    ],
    "pre": [
      {
        "description": "upperBound must be non-negative",
        "guard": {
          "condition": "upperBound >= 0",
          "description": "upperBound must be non-negative"
        }
      }
    ]
  }
]

我编译程序,并运行以下命令来应用 Randoop 以便根据正确性规范生成测试用例:

java -cp my-classpath:$RANDOOP_JAR randoop.main.Main gentests --testclass=com.example.math.Math --output-limit=200 --specifications=spec.json

spec.json包含上述方法合同规范的 JSON 文件在哪里。我有两个问题:

  1. 为什么不改变--output-limit生成的测试用例的数量?对于足够大的数字,似乎我总是只得到 8 个回归测试用例,其中两个检查方法getClass没有返回null值(即使这不是我的规范的一部分)。请让我知道如何生成更多回归测试用例。我是否缺少命令行选项?
  2. 似乎 Randoop 在spec.json尝试生成显示错误的测试用例时并未参考内部规范。我们可以让 Randoop 在每个违反提供的后置条件的输入上生成错误显示测试用例吗?

谢谢你。

标签: junitrandooprandom-testing

解决方案


  1. 为什么不改变--output-limit生成的测试用例的数量?

Randoop 生成测试,然后输出其中的一个子集。例如,Randoop 不输出包含的测试,这些测试显示为某个较长测试的子序列。

--output-limit.

其中两个检查方法getClass不返回空值(即使这不是我的规范的一部分)

getClass()Math(被测类)中的一个方法,所以 Randoop 调用getClass(). 在测试生成时,返回值不为空,因此 Randoop 对此做出了断言。

没有什么特别的getClass();Randoop 将为其他方法创建类似的回归测试。

  1. 好像Randoop没有查阅里面的规范spec.json

Randoop 在处理静态方法的后置条件规范时存在错误。该错误已得到修复

要报告错误,最好使用Randoop 的问题跟踪器,如Randoop 手册中所述。获得帮助的选项还包括邮件列表。与 Stack Overflow 不同,问题跟踪器和邮件列表允许讨论和跟踪当前状态。谢谢!


推荐阅读