gpt4 book ai didi

java - 如何获得关于在 junit 测试中有多少 assertEquals 语句通过/失败的报告

转载 作者:行者123 更新时间:2023-11-30 10:19:06 26 4
gpt4 key购买 nike

我正在尝试测试一组由服务类生成的结果以及一些已定义的 expected 结果。该服务产生实际结果。

该服务使用来自 json 文件的值进行馈送,其中包含一些值和预期结果。使用 AssertEqualsservice 的输出与 expected 结果进行比较,只有当它们相等时测试才通过。

是否有可能在一些 AssertEquals 失败的情况下继续测试并生成一个报告,说明有多少 AssertEquals 通过或失败。

我探索了 maven surefire 但我无法获得预期的结果。

注意:只有一个 @Test 方法。在这个方法中,我只是用不同的参数多次调用服务并比较 expectedactual 结果

@Test
public void createTest() throws Exception {
try {
// some other code to read the file
JSONParser parser = new JSONParser();
// ruleValidationResourcePath is location of the file
JSONArray array = (JSONArray) parser.parse(new FileReader(ruleValidationResourcePath));
//looping this json and passing each object values to a service
for(Object o:array){
JSONObject rulesValidation = (JSONObject) o;
String ruleAdExpr = (String) rulesValidation.get("ruleA");
String _result = (String)rulesValidation.get("result");
PatObj patObj= new PatObj ();
patObj.setRule(ruleAdExpr.trim());
//service is an instance of class which hold props method
PatObj pat = service.props(patObj);
if(patObj.getRule() != null){
String _machineRule =pat .getMachine_rule().toLowerCase().trim();
String expResult = _result.toLowerCase().trim();
// here some _machineRule & expResult may be different
// currently test is failing if they are not equal
// will like to continue test even if they are not equal
// and create report of how many failed/passed

Assert.assertEquals(_machineRule,expResult);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

最佳答案

Is it possible to continue test even if some AssertEquals fails.

是的,这是可能的,但我不建议您这样做,因为这是对 JUnit 的滥用。

JUnit 方法遵循这样的规则,即测试应该只检查每个测试方法的一个特定案例。

在您的情况下,您的 JSON 加载逻辑只是一个设置,您检查具有不同参数的 getMachineRule() 方法。

JUnit 世界有自己的机制来处理此类情况。

如何正确实现:

您需要通过参数化来重新设计测试。

先加JUnitParams到您的项目。

然后您需要引入一个方法来加载 JSONArray 并将其结果用作测试的参数。

一起:

@RunWith(JUnitParamsRunner.class)
public class RoleTest {

@Test
@Parameters
public void createTest(JSONObject rulesValidation) throws Exception {
// use the same logic as you have inside your "for" loop
//...
assertEquals(machineRule, expResult);
}

private Object[] parametersForCreateTest() {
// load JSON here and convert it to array
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(
new FileReader(ruleValidationResourcePath)
);
return jsonArray.toArray();
}
}

这样,createTest 将根据您的 JSONArray 中的对象执行多次,您将看到每次特定运行的报告(即使某些他们失败了)。

注意方法命名很重要。返回参数的方法应以与测试方法相同的方式命名,但以 parametersFor 为前缀 - 在您的情况下为 parametersForCreateTest。在 the documentation 中查找更多示例.

关于java - 如何获得关于在 junit 测试中有多少 assertEquals 语句通过/失败的报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847978/

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