NotSteve's avatar

How to test Json Structures properly?

I'm learning how to test properly using PHPUnit with Laravel, and I noticed that whenever I try to test the json structure of data I am pulling in from a request, it passes no matter how the 'assertJsonStructure' is actually structured.

For example, I have a dataset similar to this:

{
	"data": [{
		"id":"1",
		"attributes": {
			"ticker_symbol": "CVS",
			"company_name": "CVS Health Corp",
			"confidence": "97.34",
			"predictions": {
				"day 1": 100,
				"day 2": 99.99,
				"day 3": 11.23,
				"day 4": 112.23,
				"day 5": 11.23,
				"day 6": 121.23,
				"day 7": 15.23,
				"day 8": 166.23,
				"day 9": 162.23,
				"day 10": 159.23
			}
		}
	}]
}

And corresponding testing code:

  public function test_get_all_stock_predictions()
    {
        $response = $this->get('api/stockpredictions');

        $response->assertStatus(200);

        $response->assertJsonStructure(
            [
                'data' => [
                    '*' => [
                        'id',
                        'attributes' => [
                            'ticker_symbol',
                            'company_name',
                            'confidence',
                            'predictions' => [
                                'day 1',
                                'day 2',
                                'day 3',
                                'day 4',
                                'day 5',
                                'day 6',
                                'day 7',
                                'day 8',
                                'day 9',
                                'day 10',
                            ]
                        ]
                    ]
                ]
            ]
        );
    }    									

It passes every time I run my tests. Even if I remove one of the "days" in the json structure. I want to know how to fail this test using the assertJsonStructure so that in the future, I can make proper test.

Please let me know if I am going about this the wrong way.

0 likes
1 reply
tisuchi's avatar

@sgfanega If you try this, does it work?

    public function test_stock_predictions_api_response()
    {
        // Make the API call
        $response = $this->get('api/stockpredictions');

        // Check the response status
        $response->assertStatus(Response::HTTP_OK);

        $response->assertJson([
            'data' => [
                [
                    'id' => '1',
                    'attributes' => [
                        'ticker_symbol' => 'CVS',
                        'company_name' => 'CVS Health Corp',
                        'confidence' => '97.34',
                    ]
                ]
            ]
        ]);
    }

Please or to participate in this conversation.