当表达式包含连字符

时间:2018-02-26 04:31:16

标签: php json testing codeception jsonpath

我正在使用codeception来测试我的JSON API laravel项目。我正在使用codeception的JSONPath函数来检查响应的结构。当包含连字符时,我无法解析表达式。 Json Path使用连字符作为减法运算符,但在这种情况下我将它用作字符串。我知道将包含hyohen的子字符串放在单引号中的整个表达式中的双引号(“”)内应该这样做。但它不起作用。

这是我的api测试套件SomeTestCest.php上的函数

public function someTest(ApiTester $I)
{
    $I->sendGET('/teachers/122');
    //used double quotes as it contains hyphen
    $I->seeResponseJsonMatchesJsonPath('$.data.[*].relationships."high-schools"');
}

这是测试中get请求的示例响应。

{
    "data": {
        "type": "teachers",
        "id": "122",
        "attributes": {
            "fullname": "Rhoda Frami",
        },
        "relationships": {
            "high-schools": {
                "data": null
            },
            "subjects": {
                "data": null
            }
        },
        "links": {
            "self": "http:\/\/api.project:81\/teachers\/122"
        }
    }
}

当我使用以下

运行测试时
php codecept run tests/api/resources/SomeTestCest.php --steps --verbose

它会抛出错误

There was 1 failure:

---------
1) SomeTestCest:
 Test  tests/api/resources/SomeTestCest.php:someTest
 Step  See response json matches json path "$.data.[*].relationships."high-schools""
 Fail  Received JSON did not match the JsonPath `$.data.[*].relationships."high-schools"`.
Json Response: 
    {
    "data": {
        "type": "teachers",
        "id": "122",
        "attributes": {
            "fullname": "Rhoda Frami",
        },
        "relationships": {
            "high-schools": {
                "data": null
            },
            "subjects": {
                "data": null
            }
        },
        "links": {
            "self": "http:\/\/api.project:81\/teachers\/122"
        }
    }
}

我也试过以下方法

$I->seeResponseJsonMatchesJsonPath("$.data.[*].relationships.'high-schools'");

$I->seeResponseJsonMatchesJsonPath('$.data.[*].relationships."high-schools"');

$I->seeResponseJsonMatchesJsonPath('$.data.[*].relationships.high-schools');

$I->seeResponseJsonMatchesJsonPath("$.data.[*].relationships.high-schools");

并且它或者是这个错误。我知道它,因为连字符没有被解析为预期。

There was 1 error:

---------
1) SomeTestCest: 
 Test  tests/api/resources/SomeTestCest.php:SomeTest

  [Flow\JSONPath\JSONPathException] Unable to parse token high-schools in expression: .data.[*].relationships.high-schools 

所以我检查了代码使用的基础包JSONPath,发现它按预期工作。

$data = ['people' => [['high-schools' => 'Joe'], ['high-schools' => 'Jane'], ['high-schools' => 'John']]];
$result = (new \Flow\JSONPath\JSONPath($data))->find('$.people.*."high-schools"');
print_r($result);

这是结果

Flow\JSONPath\JSONPath Object
(
    [data:protected] => Array
        (
            [0] => Joe
            [1] => Jane
            [2] => John
        )

    [options:protected] => 0
)
=> true

所以我的问题是如何使用带有Json Path的Codeception来解析包含连字符( - )的json字符串以检查json的结构?

谢谢

0 个答案:

没有答案