使用Randoop生成测试用例(基于前后条件)

时间:2019-02-10 02:40:08

标签: junit randoop random-testing

我正在尝试使用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在每个违反提供的后置条件的输入上生成错误显示测试用例吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

这在documentation for --output-limit中被倾斜提及。

  

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

getClass()Math(被测类)中的方法,因此Randoop调用getClass()。在测试生成时,返回值不为null,因此Randoop对此进行了断言。

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

  
      
  1. Randoop似乎没有参考spec.json内的规范
  2.   

Randoop处理静态方法的后置条件规范时有一个错误。该错误是fixed

要报告错误,最好使用Randoop's issue tracker,如Randoop manual中所述。 getting help的选项还包括邮件列表。与Stack Overflow不同,问题跟踪器和邮件列表允许讨论并跟踪当前状态。谢谢!

相关问题