【问题标题】:Prevent laravel testing $this->get() from throwing HTTP exception when status code is not 200防止 laravel 测试 $this->get() 在状态码不是 200 时抛出 HTTP 异常
【发布时间】:2017-10-14 03:44:01
【问题描述】:

我使用 laravel 5.4。在我的测试中,我会执行以下操作:

$this->get("/api/test")->assertStatus(422)->assertJson([
        "status" => "ok"
]);

当状态码为 422 时,我得到了一个 HttpException,尽管我已经完全准备好了——而且我什至期待它。我的问题是异常阻止了我的断言,因此assertJson 不起作用。

$this->expectException(HttpException::class) 没有帮助,因为它捕获了这个异常并停止了,所以这开始通过了:

$this->expectException(HttpException::class)
$this->get("/api/test")->assertStatus(422)->assertJson([
        "status" => "ok"
]);
$this->assertTrue(false);

我知道我可以自己捕获这个异常,但是我将无法以简单的方式将我的断言应用于响应。我该如何解决这个问题?

【问题讨论】:

标签: php laravel phpunit


【解决方案1】:

验证错误只会在 json 或 ajax 请求上转换为 json 响应。试试这个。

$this->getJson("/api/test")->assertStatus(422)->assertJson([
        "status" => "ok"
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2018-12-30
    • 2015-10-28
    • 2020-08-18
    • 1970-01-01
    • 2017-06-25
    • 2014-03-25
    相关资源
    最近更新 更多