Reputation: 6973
I have a Cest with a _before() that has the following code in it to authenticate (API testing):
// 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;
When I run the test I get the following error:
[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
is $this->api_token = json_decode($I->grabResponse())->token;
It appears as if $I
is no longer an object, but I have confirmed that it is still an instance of ApiTester
. So the only thing I can think of is the call to the property of a non-object is somewhere deeper down.
How can I tell where? I'm running this with the --debug
switch enabled.
[EDIT] This isn't a problem with the json_decode
. If I move $I->grabResponse()
up then the error will be on that line.
Upvotes: 1
Views: 651
Reputation: 14100
Validate response before using it.
seeResponseJsonMatchesJsonPath checks if the element is present in json response.
$I->seeResponseJsonMatchesJsonPath('$.token');
Also it could be useful to use grabDataFromResponseByJsonPath method instead of parsing it yourself.
$this->api_token = $I->grabDataFromResponseByJsonPath('$.token')[0];
[0]
is necessary because grabDataFromResponseByJsonPath returns a list of matching items.
You may need to install flow/jsonpath
library to get JsonPath methods working if it isn't installed yet.
Upvotes: 2