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

Laravel 11使用Pest测试时出现Call to a member function connection() on null错误求助

问题描述

在Laravel 11中使用Pest结合Spatie RouteTesting包进行API路由测试时,执行php artisan test报错:

ERROR Call to a member function connection() on null

测试代码(tests/Feature/RouteApiTest.php):

namespace Tests\Feature;

use App\Models\Agenda;
use function Spatie\RouteTesting\routeTesting;

routeTesting('all api routes')
    ->include('api/*')
    ->bind('agenda', Agenda::factory()->create())
    ->assertSuccessful();

tests/Pest.php配置:

uses(
    Tests\TestCase::class,
    RefreshDatabase::class,
)->beforeEach(function () {
    Artisan::call('migrate --force');
})->in('Feature');

.env.testing配置:

DB_CONNECTION=sqlite
DB_DATABASE=:memory:
APP_DEBUG=true
问题原因及解决步骤

1. 移除重复的迁移操作

RefreshDatabase trait已经自动完成数据库迁移、重置的全流程,你在beforeEach中手动调用Artisan::call('migrate --force')会触发数据库连接初始化冲突——内存SQLite数据库会在每个测试前重建,手动迁移会在连接未完全就绪时执行,从而引发connection() on null错误。

修改tests/Pest.php,删除手动迁移代码:

uses(
    Tests\TestCase::class,
    RefreshDatabase::class,
)->in('Feature');

2. 延迟模型实例创建

Spatie的routeTesting可能在数据库连接完全初始化前尝试创建模型,将模型绑定改为闭包形式,延迟实例创建时机:

routeTesting('all api routes')
    ->include('api/*')
    ->bind('agenda', fn() => Agenda::factory()->create())
    ->assertSuccessful();

3. 验证测试环境配置加载

确保Laravel测试时正确读取.env.testing,可在测试中临时添加验证代码:

dd(env('DB_CONNECTION'), env('DB_DATABASE'));

若输出不是sqlite和:memory:,需检查:

  • .env.testing是否在项目根目录
  • 执行测试时是否明确指定测试环境:php artisan test --env=testing

4. 确认包版本兼容Laravel 11

检查composer.json中spatie/laravel-route-testing的版本,确保支持Laravel 11,版本过低则执行更新:

composer require spatie/laravel-route-testing:^3.0 --dev

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:37:07