下面是一个使用JUnit的参数化测试的例子:
java复制插入
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class ParameterizedTest {
private int input;
private int expected;
public ParameterizedTest(int input, int expected) {
this.input = input;
this.expected = expected;
}
@Parameters
public static Collection<Object[]> testCases() {
return Arrays.asList(new Object[][] {
{ 2, 4 },
{ 0, 0 },
{ -3, 9 },
{ 10, 100 }
});
}
@Test
public void testSquare() {
assertEquals(expected, square(input));
}
private int square(int num) {
return num * num;
}
}
复制插入
在上面的例子中,我们使用了JUnit的@RunWith(Parameterized.class)
注解来指定使用参数化测试运行器。然后,我们定义了一个构造函数来接收测试参数,并在注解@Parameters
的方法中返回测试用例的集合。测试用例的集合是一个包含参数数组的集合,其中每个参数数组都表示一个测试用例。在我们的例子中,我们定义了四个测试用例:{2, 4},{0, 0},{-3, 9}和{10, 100}。
在@Test
注解的测试方法中,我们使用assertEquals
断言来比较实际结果和期望结果。我们调用square
方法来计算输入参数的平方,并与期望结果进行比较。
当我们运行该测试类时,JUnit会自动根据@Parameters
注解的方法生成多个测试实例,并为每个测试实例调用@Test
注解的测试方法。
制作不易,请点赞加关注