Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Strawberry_Sacha's avatar

assertJsonFragment fails because date object is in slightly different order

I'm using assertJsonFragment to assert that my API is returning an object properly.

It fails with the following (example) message:

Unable to find JSON fragment:
   │
   │ [{"created_at":{"date":"2019-01-31 15:40:08.000000","timezone_type":3,"timezone":"UTC"}}]
   │
   │ within

     // (and then the entire JSON response)

However, the response does contain the date object...

"created_at":{"date":"2019-01-31 15:40:08.000000","timezone":"UTC","timezone_type":3}

Notice that timezone and timezone_type are swapped in the response.

I'm using the same resource object to generate the expected result as I am in the controller.

I suppose my questions are:

  • why are they swapped?

  • can I do a more "loose" assertion, still using assertJsonFragment?

0 likes
1 reply
D9705996's avatar

Not 100% sure why order is in this way (I think its order a-z)... however I have always avoided relying on key order(learnt the hard way in Perl which doesn't enforce key order in hashes). What you could do here is three assertJsonFragments on each of the keys but TBH I normally just decode the json and store in a variable then use phpunit assertions

e.g. $this->assertEquals('UTC',$response['created_at']['timezone']);

Remember the client consuming your api won't care about the order of the keys (it certainly shouldnt)

Please or to participate in this conversation.