首页 > 解决方案 > HttpFoundation JsonResponse 在 PhpUnit 测试中返回 Null

问题描述

我有一个使用 Botman 的 Laravel 8 应用程序。当我从 Postman 调用端点时,我得到了带有正确标题的正确内容。但是当我在测试时调用端点时,我得到了空的内容,因此测试没有通过。响应由 HttpFoundation JsonResponse 处理。奇怪的是内容打印在测试控制台中(即使我不转储)但是,$response->dump() 返回 Null。

我的测试方法

 /** @test */
public function user_can_talk_to_coach()
{
    Passport::actingAs($this->learner, $this->learnerScopes);

    $response = $this->postJson(
        'learner/v1/coach',
        [
            'driver'  => 'mobile',
            'userId'  => 1,
            'message' => null,
            'intent'  => 'intent_testing',
        ],
        $this->headers
    );

    var_dump('dump');
    $response->dump();
    var_dump('headers');
    $response->dumpHeaders();

    $response->assertStatus(200)
    ->assertJson([
        'data' => [
            [
                'type'                 => 'text',
                'text'                 => 'Hey',
                'attachment'           => null,
                'additionalParameters' => [
                    'node'=> 'testing',
                ],
            ],
        ],
    ]);
}

消息发送方式

/**
 * Send out message response.
 */
public function messagesHandled()
{
    $messages = $this->buildReply($this->replies);

    // Reset replies
    $this->replies = [];

    $response = new JsonResponse();
    $response->setData(['data' => $messages]);
    $response->send();
}

测试结果捕获

知道这里发生了什么吗?

标签: jsonlaraveltestingphpunitresponse

解决方案


推荐阅读