【发布时间】:2017-05-03 05:30:08
【问题描述】:
我开发了一个基于 Web 的应用程序,在某种程度上让用户只需输入值即可提交测试用例,而不是编写完整的 JUnit 测试。
我目前使用的方式是为每次提交生成一个测试类,然后编译并运行。
例如假设我们有一个像下面这样的类:
public class CalculatorO
{
public boolean isPrime( int n )
{
if (n < 2) {
return false;
}
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
作为 oracle,以及像下面这样的另一个类:
public class CalculatorM0
{
public boolean isPrime( int n )
{
if (n < 2) {
return false;
}
int count = 0;
for (int i = 1; i <= n; i++) {
if (n * i == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
作为测试的对象。然后我生成一个测试模板如下:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals;
import org.junit.Test;
public class {{TestClassName}} {
@Test
public void {{MethodName}}() {
int AO = {{valueA}};
int AM = {{valueA}};
{{OriginalClassName}} {{OriginalClassNameLower}} = new {{OriginalClassName}}();
{{MutantClassName}} {{MutantClassNameLower}} = new {{MutantClassName}}();
{{MethodReturnType}} resultO = {{OriginalClassNameLower}}.{{MethodName}}(AO);
{{MethodReturnType}} resultM = {{MutantClassNameLower}}.{{MethodName}}(AM);
assertEquals(resultO, resultM);
}
}
然后,例如,当用户提交数字 3 作为输入值时,我会像这样操作测试模板:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals;
import org.junit.Test;
public class CalculatorOCalculatorM0Test30099 {
@Test
public void isPrime() {
int AO = 3;
int AM = 3;
CalculatorO calculatorO = new CalculatorO();
CalculatorM3 calculatorM3 = new CalculatorM3();
boolean resultO = calculatorO.isPrime(AO);
boolean resultM = calculatorM3.isPrime(AM);
assertEquals(resultO, resultM);
}
}
然后我编译测试用例并运行它。
主要问题是这种循环经常发生,并且由于强制加载到服务器上,因为文件被创建和编译,服务器面临内存不足和崩溃的问题。
我正在寻找一种方法来创建一次测试用例并构建一次,然后为每个带有参数的输入运行它。
我的意思是这样的:
java -cp .;../../JUnitLibs/junit-4.12.jar;../../JUnitLibs/hamcrest-core-1.3.jar org.junit.runner.JUnitCore CalculatorOCalculatorM0Test30099 > CalculatorOCalculatorM0Test30099Result -input 3
【问题讨论】:
-
我使用 Zohhak 进行参数化测试:piotrturski.github.io/zohhak
-
@Dawood ibn Karim,这样参数应该在构建文件之前出现在测试类中。但是我提到的论点(参数)在运行时很快就出现了。
-
虽然很长一段时间来自发布的答案,但从那时起我正在使用这个解决方案并且它是完美的。如果有人需要源代码示例,我也可以分享。谢谢@GhostCat。
-
@GhostCat,我想我没有明白你的真正意思。如果有什么我可以做的,请告诉我。感谢您的精彩回答。
标签: java junit arguments parameterized