【问题标题】:How do I resolve error Call to undefined method assertSessionHasErrors in laravel unit tests?如何解决 laravel 单元测试中对未定义方法 assertSessionHasErrors 的错误调用?
【发布时间】:2021-11-23 11:36:02
【问题描述】:

使用 Laravel 8,我正在运行一些单元测试,但在我的一个测试中出现此错误:

Call to undefined method Tests\Unit\ApplicationTest::assertSessionHasErrors()
use Tests\TestCase;
class ApplicationTest extends TestCase {
...
    $applicationRef = Application::inRandomOrder()->pluck('reference')->first();
    $this->post(
        'http://website.test/applications/'.$applicationRef.'/update',
        ['title' => null]
    );

    $this->assertSessionHasErrors('title');
}

我已经尝试了各种方法来测试表单验证,但都无法正常工作。任何意见,将不胜感激。谢谢

【问题讨论】:

    标签: laravel unit-testing phpunit


    【解决方案1】:

    您必须将$this->post 的结果存储在一个变量中并使用它。

    $applicationRef = Application::inRandomOrder()->pluck('reference')->first();
    $response = $this->post(
        'http://website.test/applications/'.$applicationRef.'/update',
        ['title' => null]
    );
    
    $response->assertSessionHasErrors('title');
    

    【讨论】:

    • 感谢@matiaslauriti,但是,使用您的示例返回错误会话缺少预期的键[错误]。断言 false 为 true 失败。有什么想法吗?
    • 这意味着您的控制器没有返回任何错误。我的代码是正确的,它在断言它应该做什么。你能分享你的控制器吗?
    猜你喜欢
    • 2015-10-09
    • 2017-08-24
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2021-09-16
    • 2017-05-28
    • 1970-01-01
    • 2018-03-05
    相关资源
    最近更新 更多