gpt4 book ai didi

java - 如何编写带参数的单元测试?

转载 作者:行者123 更新时间:2023-12-01 16:49:07 25 4
gpt4 key购买 nike

我对 java 不熟悉,但在 c#(NUnit) 中,您可以通过添加 [TestCase] 属性来参数化单元测试,如下所示:

[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
Assert.AreEqual( q, n / d );
}

在这种情况下,我们不必为每个测试用例编写单独的单元测试。相反,我们编写 [TestCase] 来更改值。

Java 上有等效的吗?目前使用 Junit 4.12

最佳答案

参数化就是你所需要的。考虑下面的例子。请注意,test3 显然是红色的,因为 20/5 = 4。

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class DividerTest {

private int dividend;
private int divisor;
private int expectedResult;

@Parameterized.Parameters
public static Collection<Object[]> data() {
Object[] test1 = { 10, 5, 2 };
Object[] test2 = { 15, 5, 3 };
Object[] test3 = { 20, 5, 5 };

return Arrays.asList(test1, test2, test3);
}

public DividerTest(int dividend, int divisor, int expectedResult) {
this.dividend = dividend;
this.divisor = divisor;
this.expectedResult = expectedResult;
}

@Test
public void testDivider() {
assertEquals(expectedResult, dividend / divisor);
}
}

这是测试结果:

enter image description here

关于java - 如何编写带参数的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44126340/

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