首页 > 解决方案 > 如何获取带条件返回的结果并断言正确的值

问题描述

我编写了代码来断言从数据库存储的值。

//SQL statement
String dbQuery2 = /SELECT * FROM public.test where testId = 'default'/


//Connect to PostgresSQL, global variable is stored at profile
List results = CustomKeywords.'test.database.getPostgresSQLResults'(GlobalVariable.dbConnString2 , GlobalVariable.dbUsername2 , GlobalVariable.dbPassword2 ,GlobalVariable.dbDriver2 ,dbQuery2 )
println(results)


//print the "test_info" column
String test_info = results.get(0).get('test_info')
println(test_info)

//convert to json format and verify result
def test_infojson = new JsonSlurper().parseText(new String(test_info))
println('Database test_info response text: \n' + JsonOutput.prettyPrint(JsonOutput.toJson(test_infojson)))

返回的结果是:

{
    "testId": "default",
    "testLines": [
        {
            "testId": "TC-1",
            "name": "a",
            "isDeleted": true
        },
        {
            "testId": "TC-1",
            "name": "b",
            "isDeleted": false
        },
                {
            "testId": "TC-2",
            "name": "c",
            "isDeleted": true
        },
        {
            "testId": "TC-2",
            "name": "d",
            "isDeleted": false
        }
    ],
}

然后我使用断言:

assertThat(test_infojson.testLines[0].name).isEqualTo("b")

这个断言是错误的,因为结果中有2个testId,一个isDeleted = true,另一个是false。

什么应该是正确的断言,以获取 testLines 其中 "testId": "TC-1" 和 "isDeleted": false 所以断言值为 "name": "b"

我正在使用 org.assertj.core.api.Assertions.* 任何其他断言类都可以。

标签: assertassertionassertj

解决方案


对于 JSON 断言,我建议使用https://github.com/lukas-krecan/JsonUnit


推荐阅读