I’m in the process of upgrading an API code base that has been in production since Laravel 5, and continues to evolve. The bulk of the update to version 8 went smoothly, but one breaking change that I couldn’t find documented anywhere held me up for some time this afternoon.
A great many of the tests use a pattern of getting a response from an endpoint, running $data = $response->decodeResponseJson()
, and then making assertions against the resulting PHP array in $data
. Unfortunately, in Laravel 8 the return type is now \Illuminate\Testing\AssertableJsonString
, and I kept running into errors such as:
Argument #2 of PHPUnit\Framework\Assert::assertArrayHasKey() must be an array or ArrayAccess
I made various attempts to convert the output of decodeResponseJson
into an array (and being confused as to why it didn’t work, since AssertableJsonString implements ArrayAccess
), but in the end the solution was simple.
Instead of refactoring every existing test to use Laravel’s new JSON-based assertions, I merely had to change each call to decodeResponseJson
to just json
. That is, switching to
1 |
$data = $response->json(); |
was all it took.