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

如何用PEST和Laravel测试AppServiceProvider中是否调用Model::shouldBeStrict

问题翻译

我想要测试AppServiceProvider中是否调用了Model::shouldBeStrict。我尝试了以下代码:

it('will use Model::shouldBeStrict', function () {
    $user = User::factory()->create();
    $a = $user->notExistingAttribute;
})->throws(Exception::class);

但没有抛出异常,请问我该如何进行测试?


解决方法

1. 捕获正确的异常类

Model::shouldBeStrict()开启后,访问不存在的模型属性会抛出**Illuminate\Database\Eloquent\AttributeNotFoundException**,而非通用的Exception。修改测试代码指定正确的异常类:

use Illuminate\Database\Eloquent\AttributeNotFoundException;

it('enables strict model mode via AppServiceProvider', function () {
    $user = User::factory()->create();
    $user->notExistingAttribute;
})->throws(AttributeNotFoundException::class);

2. 直接验证方法调用

如果仍不生效,可通过Mock验证shouldBeStrict是否被正确调用,避免依赖属性访问的间接测试:

use Illuminate\Database\Eloquent\Model;

it('calls Model::shouldBeStrict in AppServiceProvider', function () {
    $this->mock(Model::class, function ($mock) {
        $mock->shouldReceive('shouldBeStrict')->once();
    });

    // 重新加载应用以触发AppServiceProvider的boot逻辑
    $this->refreshApplication();
});

3. 确认Provider加载状态

检查config/app.php的providers数组,确保App\Providers\AppServiceProvider::class在列表中,且测试环境未排除该Provider。若测试类使用了RefreshDatabase特性,无需额外调整,它不会影响Provider的加载逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:32:05