You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel测试驱动部署:删除记录测试用例报错求助

Laravel 删除测试用例问题排查

先贴出你的测试代码:

public function a_user_can_delete_the_task(){
    $data = [
        'title' => 'abc',
        'description' => 'xyz'
    ];
    $post = Post::create($data);
    //When the user hit's the endpoint to update the task
    $response = $this->delete('/api/v1/delete/'.$post->id, $post->toArray());
    $response->dump();
}

以下是几个核心问题及修复方案:

  • DELETE请求参数错误:Laravel的delete()方法第二个参数是请求头数组,不是请求体数据。DELETE请求无需传递实体内容,直接去掉第二个参数即可:

    $response = $this->delete('/api/v1/delete/'.$post->id);
    
  • 路由格式不规范(可能导致404):RESTful风格的删除路由通常定义为/api/v1/posts/{post}(对应控制器的destroy方法),你当前的/api/v1/delete/{id}格式不符合规范,先检查routes/api.php里的路由是否正确绑定了删除逻辑,比如是否用了资源路由:

    Route::apiResource('posts', PostController::class);
    

    如果用资源路由,删除请求地址应该是/api/v1/posts/'.$post->id。

  • 缺少必要的测试断言:当前测试仅dump响应,无法验证删除操作是否成功,建议添加数据库断言:

    $this->assertDatabaseMissing('posts', ['id' => $post->id]);
    
  • 可选验证:确认模型创建成功:可以在创建后添加一行代码,确保记录确实写入数据库:

    $this->assertNotNull($post->id);
    
  • 注释错误:注释写的是"update the task",但实际是删除操作,建议修正避免混淆。

内容的提问来源于stack exchange,提问作者VINA NIKAM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 23:03:27