【问题标题】:how to write test for json response?如何为json响应编写测试?
【发布时间】:2017-10-08 18:52:41
【问题描述】:

我有函数返回 JSON

return response()->json([
            'status' => 'OK',
            'data' => [
                'id' => $routeForecast->id,
            ],
        ])

我怎样才能对此进行测试.. 我的 laravel 版本是 5.1,我使用了 assertJson([ ]) 它给了我这个错误

***** PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertJson() must be a string

并尝试seeJson它给我这个错误

***** Invalid JSON was returned from the route. Perhaps an exception was thrown?

我该如何解决??

【问题讨论】:

    标签: php json unit-testing laravel-5 laravel-5.1


    【解决方案1】:

    试试这样的。

        // When
        $response = $this->getJson( 'v1/helloWorld' );
    
        //dd( $response ); // perhaps die and dump here to check response?
    
        // Then
        $response
            ->assertStatus( 200 )
            ->assertJson( [
                'status' => 'OK',
            ] );
    

    【讨论】:

    • 我认为 assertJson 不适用于 laravel 5.1
    • 这是我为响应所做的 $response = $this->json('POST', '/path/en');
    • 啊抱歉,它在 5.1 中是 seeJson
    • 是这样吗? $response = $this->json('POST', '/path/en');
    • 不,看起来你应该这样做 $this->post('/path/en')$this->call('POST', '/path/en'); - laravel.com/docs/5.1/testing#testing-json-apis
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2018-01-18
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多