问题现象
测试代码
@Test @Description("查询部门") @DisplayName("查询部门") void listDepartment() { String createName = "CreateName" + FakeUtils.getTimeStamp(); String createNameEn = "CreateNameEn" + FakeUtils.getTimeStamp(); Response creatResponse = DepartmentApiObject.createDepartment(createName,createNameEn,accessToken); departmentId = creatResponse.path("id") != null ? creatResponse.path("id").toString() : null; Response listResponse = DepartmentApiObject.listDepartment(departmentId, accessToken); assertEquals("1", listResponse.path("errcode").toString()); assertEquals(departmentId+"1", listResponse.path("department.id[0]").toString()); assertEquals(createName+"1", listResponse.path("department.name[0]").toString()); assertEquals(createNameEn+"1", listResponse.path("department.name_en[0]").toString()); }
执行结果:
org.opentest4j.AssertionFailedError: Expected :1 Actual :0 <Click to see difference>
备注:有四个断言,预期都是错误的,想让程序一次性的暴露出来,提高效率
问题原因
因为原来使用的是junit5的普通断言,当一个断言失败会直接跳出测试方法,导致后面的断言无法执行,此时的脚本容错性比较低
解决思路
使用软断言,即使一个断言失败,仍会进行余下的断言,然后统一输入所有断言结果
解决方案
使用junit5提供的java8 lambdas的断言方法,当一个断言失败,剩下的断言仍会执行,脚本容错性增强
示例代码
@Test @Description("查询部门") @DisplayName("查询部门") void listDepartment() { String createName = "CreateName" + FakeUtils.getTimeStamp(); String createNameEn = "CreateNameEn" + FakeUtils.getTimeStamp(); Response creatResponse = DepartmentApiObject.createDepartment(createName,createNameEn,accessToken); departmentId = creatResponse.path("id") != null ? creatResponse.path("id").toString() : null; Response listResponse = DepartmentApiObject.listDepartment(departmentId, accessToken); assertAll("返回值校验", ()->assertEquals("1", listResponse.path("errcode").toString()), ()->assertEquals(departmentId+"1", listResponse.path("department.id[0]").toString()), ()->assertEquals(createName+"1", listResponse.path("department.name[0]").toString()), ()->assertEquals(createNameEn+"1", listResponse.path("department.name_en[0]").toString())); }
执行结果:
expected: <1> but was: <0> Comparison Failure: Expected :1 Actual :0 <Click to see difference> expected: <21> but was: <2> Comparison Failure: Expected :21 Actual :2 <Click to see difference> expected: <CreateName16259022759441> but was: <CreateName1625902275944> Comparison Failure: Expected :CreateName16259022759441 Actual :CreateName1625902275944 <Click to see difference> expected: <CreateNameEn16259022759441> but was: <CreateNameEn1625902275944> Comparison Failure: Expected :CreateNameEn16259022759441 Actual :CreateNameEn1625902275944 <Click to see difference> org.opentest4j.MultipleFailuresError: 返回值校验 (4 failures) ...