【问题标题】:"Trying to get property of non-object" error when running a Codeception test运行 Codeception 测试时出现“尝试获取非对象的属性”错误
【发布时间】:2017-10-17 13:43:29
【问题描述】:

我有一个带有 _before() 的 Cest,其中包含以下代码来进行身份验证(API 测试):

// Log a user in
$I->haveHttpHeader('Accept', 'application/json');
$I->sendPOST('/authentication/login', ['username' => $this->username, 'password' => $this->password]);

$this->api_token = json_decode($I->grabResponse())->token;

当我运行测试时,我收到以下错误:

[PHPUnit_Framework_Exception] Trying to get property of non-object  


Scenario Steps:

 3. $I->grabResponse() at tests/api/ApiBase.php:19
 2. $I->sendPOST("/authentication/login",{"username":"user@examplecom","password":"abc123"}) at tests/api/ApiBase.php:17
 1. $I->haveHttpHeader("Accept","application/json") at tests/api/ApiBase.php:16

tests/api/ApiBase.php:19$this->api_token = json_decode($I->grabResponse())->token;

看起来$I 似乎不再是一个对象,但我已经确认它仍然是ApiTester 的一个实例。所以我唯一能想到的是对非对象属性的调用在更深的地方。

我怎么知道在哪里?我在启用--debug 开关的情况下运行它。

[编辑] 这不是json_decode 的问题。如果我将$I->grabResponse() 向上移动,则错误将出现在该行。

【问题讨论】:

标签: php phpunit codeception


【解决方案1】:

在使用之前验证响应。
seeResponseJsonMatchesJsonPath 检查元素是否存在于 json 响应中。

$I->seeResponseJsonMatchesJsonPath('$.token');

另外,使用grabDataFromResponseByJsonPath 方法而不是自己解析它可能很有用。

$this->api_token = $I->grabDataFromResponseByJsonPath('$.token')[0];

[0] 是必需的,因为 grabDataFromResponseByJsonPath 返回匹配项的列表。

如果尚未安装,您可能需要安装 flow/jsonpath 库才能使 JsonPath 方法正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2019-03-21
    • 2016-12-23
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多