【发布时间】: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() 向上移动,则错误将出现在该行。
【问题讨论】:
-
可能json_decode的返回值不是一个对象,所以它没有“token”属性。您应该添加 json_decode 错误处理 (stackoverflow.com/questions/2348152/…)
标签: php phpunit codeception