dsiimyoc804955 2017-02-02 10:52 采纳率: 100%
浏览 377
已采纳

在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]]
  • 写回答

1条回答 默认 最新

  • duangouyan3328 2017-02-03 05:51
    关注
    $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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?