在Laravel中测试POST调用时如何传递多维数组?

问题描述:

I'm testing a POST method in my project and it calls for a multidimensional array as a parameter. How do I pass this through Laravel's post() method? I'm also trying the postJson() method. The multi-array I'm testing is filters["excludes"]:

public function testExcludeFilter()
    {
        $json = '
        {
            "northLatitude":45.123456,
            "southLatitude":45.123456,
            "eastLongitude":9.1234567,
            "westLongitude":9.1234567,
            "filters": {
                "excludes": [
                    1
                ]
            }
        }
        ';

        $response = $this->postJson('api/v1/getHotels', $json)
            ->dontSeeJson([
                'id' => 1,
                'name' => 'Hotel-1',
                'latitude' => 45.123456,
                'longitude' => 9.1234567
                ]);

        $response->assertResponseStatus(200);
    }

Error received:

ErrorException: Argument 2 passed to Illuminate\Foundation\Testing\TestCase::postJson() must be of the type array, string given

I also tried to pass my data as an array, but it did not pay attention to the exclude filter:

postJson('api/v1/getHotels', ['northLatitude' => '45.123456', 'southLatitude' => '45.123456', 'westLongitude' => '9.1234567', 'eastLongitude' => '9.1234567', 'filters["excludes"]' => [1]]

$response = $this->postJson('api/v1/getHotels', json_decode($json, true))
            ->dontSeeJson([
                'id' => 1,
                'name' => 'Hotel-1',
                'latitude' => 45.123456,
                'longitude' => 9.1234567
                ]);

Json_decode($json, true) will convert your json data to array.