简体   繁体   中英

Testing JSON response with Laravel

I prepared a sample API with Laravel. It always returns this object:

{
    "a": 1,
    "b": 2
}

Now, I'd like to understand better how to test it with phpunit . I found there are assertJson and assertJsonFragment methods and I fail to understand the difference between them.

Let's say I'd like to assert the exact structure of the response, so it needs to be a=1 and b=2 , nothing more, nothing less. At first, I was sure this would work:

$response = $this->get('/api/foo');

$response->assertStatus(200)
         ->assertJson(['a' => 1, 'b' => 2]);

It will pass the test, but the problem is that it still passes the test if I add more properties to the response, like c=3 or whatever. Then there is assertJsonFragment method which, for my tests, behaves the same, just giving different error messages.

Is assertJson buggy? Is there any other way to do what I'm trying to do, which is to just make sure the response is this particular set of properties?

Tested on Laravel 5.6 and 5.7.

From here :

The assertJson method converts the response to an array and utilizes PHPUnit::assertArraySubset to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

And more importantly, to achieve what you want:

If you would like to verify that the given array is an exact match for the JSON returned by the application, you should use the assertExactJson method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM