gpt4 book ai didi

java - JUnit 两个变量迭代各自的值集,创建测试函数

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:18:50 31 4
gpt4 key购买 nike

检查函数有两个参数,我想为各个域的笛卡尔积的每个元素都有一个测试用例,但不需要像中那样手动编写所有测试用例

void check(Integer a, Integer b) { ... }

@Test
public void test_1_2() { check(1, 2); }

...

在 python 中我会选择

class Tests(unittest.TestCase):
def check(self, i, j):
self.assertNotEquals(0, i-j)



for i in xrange(1, 4):
for j in xrange(2, 6):
def ch(i, j):
return lambda self: self.check(i, j)
setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))

我如何使用 Java 和 JUnit 做到这一点?

最佳答案

有了理论你可以写这样的东西:

@RunWith(Theories.class)
public class MyTheoryOnUniverseTest {

@DataPoint public static int a1 = 1;
@DataPoint public static int a2 = 2;
@DataPoint public static int a3 = 3;
@DataPoint public static int a4 = 4;

@DataPoint public static int b2 = 2;
@DataPoint public static int b3 = 3;
@DataPoint public static int b4 = 4;
@DataPoint public static int b5 = 5;
@DataPoint public static int b6 = 6;

@Theory
public void checkWith(int a, int b) {
System.out.format("%d, %d\n", a, b);
}
}

(使用 JUnit 4.5 测试)

编辑

理论也会产生很好的错误信息:

Testcase: checkWith(MyTheoryOnUniverseTest):        Caused an ERROR
checkWith(a1, b2) // <--- test failed, like your test_1_2

因此您无需为测试命名即可轻松识别失败。

EDIT2

或者,您可以使用 DataPoints 注释:

@DataPoints public static int as[] = { 1, 2, 3, 4} ;
@DataPoints public static int bs[] = { 2, 3, 4, 5, 6};

@Theory
public void checkWith(int a, int b) {
System.out.format("%d, %d\n", a, b);
}

关于java - JUnit 两个变量迭代各自的值集,创建测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1187199/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com