【问题标题】:How do I console/inspect the JSON response of a Laravel Resource in PHPUnit?如何在 PHPUnit 中控制台/检查 Laravel 资源的 JSON 响应?
【发布时间】:2021-11-20 02:15:00
【问题描述】:

如何检查终端中的 JSON 响应究竟是如何从 ConversationResource 返回的?

控制器

public function show(Conversation $conversation)
{
    $conversation->load('participants');
    $messages = $conversation
        ->messages()
        ->with('sender')
        ->latest()
        ->paginate(10);

    return new ConversationResource($conversation);
}

测试

/** @test */
public function a_user_can_create_conversation_if_one_doesnt_exist()
{
    $this->withoutExceptionHandling();

    $this->actingAs($user = User::factory()->create());

    $friend = User::factory()->create();

    $response = $this->json('GET', '/api/conversation/'. $friend->id)
        ->assertStatus(201);
    
    dd($response->original);
}

【问题讨论】:

  • 因为您使用的是Resource,所以您可以利用$response->assertJsonassertJsonStructure,这取决于您要测试的内容。更多断言here.
  • 感谢您的回答。我知道如何断言Json,但我想做的是dd($response->json) sorta deal
  • 对不起,我很困惑,你到底想测试什么?您想测试架构是否正确吗?还是它返回的数据?
  • 我只是想看看在终端中使用dd(); 返回了哪些数据,就好像它的格式正确。我已经正确测试了所有内容,但有些事情我想安慰一下。我将更新我的代码
  • 如果你想dd 它那么你就没有测试/断言任何东西......

标签: laravel phpunit


【解决方案1】:

您将 $response 分配给 assertStatus() 的结果。我不知道 assertStatus 返回什么,但它可能没有 json 内容。我会尝试评估这个变量的结果

$response = $this->json('GET', '/api/conversation/'. $friend->id); 

然后

dd($response);

另外,设置 xdebug 和单步调试代码也不错,但特别是对于测试来说,这并不容易。

如果这不起作用,那么只需使用 https://www.php.net/manual/en/function.file-get-contents.php 调用相同的 url 并评估变量,看看它有什么。

【讨论】:

    猜你喜欢
    • 2014-06-06
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2021-01-12
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多