【问题标题】:Laravel 5.5 testing ModelNotFoundException exception for delete api routesLaravel 5.5 测试删除 api 路由的 ModelNotFoundException 异常
【发布时间】:2018-11-23 16:03:06
【问题描述】:

我在 laravel 5.5 项目中有奇怪的行为。我已经设置并运行了一些功能测试,如果传入的 id 不存在,则需要测试特定路由是否会返回 404。我在RouteServiceProvider 中为我的Note 模型设置了显式模型绑定

Route::bind('note', function($value){
    return Note::where('id', $value)->first() ?? abort(404);
});

这适用于我的 get route 测试。下面的测试按预期通过。 ($this->headers 只是我在许多测试所需的 setUp 方法中设置的一些位)

/** @test */
public function error_received_if_note_does_not_exist()
{
    $this->withExceptionHandling();

    $response = $this->json('GET', '/api/v1/note/1', [], $this->headers);
    $response->assertStatus(404);
}

但是这个删除路由失败了……

/**
 * @test
 * @expectedException \Illuminate\Database\Eloquent\ModelNotFoundException
 */
public function error_received_if_note_not_found()
{
    $this->withExceptionHandling();

    $response = $this->json('DELETE', '/api/v1/note/1', [], $this->headers);
    $response->assertStatus(404);
}

有消息 Failed asserting that exception of type "\Illuminate\Database\Eloquent\ModelNotFoundException" is thrown.

我知道这个异常在技术上是正确的,但我想断言我得到一个 404 错误代码。

这里是 routes/api.php 文件

Route::apiResource('note', 'NoteController')->only([
    'show',
    'destroy'
]);

我正在拔头发。欢迎任何想法。

【问题讨论】:

    标签: php laravel laravel-5 phpunit


    【解决方案1】:

    我想我已经解决了这个问题,以防止其他人有这个问题。

    在删除测试中,我删除了$this->withExceptionHandling(); 行。然后允许测试通过。

    如果我在 get 测试中做同样的事情,它会失败。所以get测试需要它,而delete测试不需要。

    随机。

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2018-08-05
      • 2015-06-27
      • 2018-08-31
      • 2018-06-23
      • 2019-09-20
      • 2018-03-01
      • 1970-01-01
      • 2020-12-14
      相关资源
      最近更新 更多