【问题标题】:What is the easiest way to assert that a response object contains a specific success message?断言响应对象包含特定成功消息的最简单方法是什么?
【发布时间】:2021-11-04 23:54:12
【问题描述】:

我有一个函数返回 redirect 并成功返回 message,如下所示:

public function update(Request $request)
{
    // ...

    return redirect()->route('my.route')
        ->with('success', 'All objects have been updated.');
}

我写了一个特性测试来测试这个函数的功能。

public function test_user_can_update()
{
    $response = $this->put(route('my.route'), [
        'value' => 15
    ]);

    $response->assertStatus(302);
    $response->assertSessionHasNoErrors();

    $this->assertEquals('All objects have been updated.', $response->getSession()->get('success'));
}

有没有更简单的方法来访问会话并检查成功消息?

【问题讨论】:

    标签: php laravel testing phpunit


    【解决方案1】:

    我发现了两种更简单的方法来检查成功消息:

    $response->assertSessionHas('success', 'Änderungen gespeichert.');
    
    // or
    
    $this->assertEquals(session('success'), 'Änderungen gespeichert.');
    

    【讨论】:

    • 超级个人推荐,永远使用assertSessionHas,因为如果明天Laravel决定停止使用session helper 并替换为其他函数,你的测试将停止工作,但如果你使用assertSessionHas ,这应该由他们在内部进行更改,因此它将始终按预期方式工作。此外,使用它更具可读性。
    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多