如何在JUnit参数化测试中验证多组带布尔预期的测试用例
JUnit参数化测试参数获取解决方案
要让你的参数化测试正常遍历所有用例并完成验证,需要通过成员变量+构造方法来接收testValues()里的每组参数,具体修改步骤如下:
1. 添加成员变量存储测试参数
在测试类中定义两个成员变量,分别对应每组用例里的「输入数值」和「预期布尔结果」:
private Double inputValue; private Boolean expectedResult;
2. 编写构造方法注入参数
创建带参构造方法,JUnit会自动把testValues()中的每组数据注入到成员变量中:
public ParamaterizedTest(Double inputValue, Boolean expectedResult) { this.inputValue = inputValue; this.expectedResult = expectedResult; }
3. 修改测试方法完成断言
在测试方法里直接使用成员变量,验证输入数值与17.5的比较结果是否符合预期:
@Test public void testinputBiggerThanExpected(){ Double threshold = 17.5; // 验证输入值大于17.5的结果是否和预期一致 Assert.assertEquals(expectedResult, inputValue > threshold); }
完整修改后的代码
import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class ParamaterizedTest { // 成员变量存储每组测试参数 private Double inputValue; private Boolean expectedResult; // 构造方法注入参数 public ParamaterizedTest(Double inputValue, Boolean expectedResult) { this.inputValue = inputValue; this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection testValues() { return Arrays.asList(new Object[][] { { 18.5, true }, { 16.5, false }, { 19.5, true }, { 15.5, false }, { 20.5, true } }); } @Test public void testinputBiggerThanExpected(){ Double threshold = 17.5; Assert.assertEquals("输入值与17.5的比较结果不符合预期", expectedResult, inputValue > threshold); } }
说明:
- JUnit参数化测试会遍历
testValues()中的每一组数据,通过构造方法赋值给成员变量后,执行一次testinputBiggerThanExpected方法 - 使用
Assert.assertEquals比Assert.assertTrue更直观,能明确展示预期值与实际值的差异,还可添加自定义错误提示
内容的提问来源于stack exchange,提问作者jennifer ruurs
相关产品推荐
相关产品推荐

