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

调用Model方法时测试中Artisan Output无输出问题排查

调用Webhook模型方法后Artisan测试无输出问题

我给现有Model新增了一个Command,同Model下其他Command的测试都正常。但在这个新测试和Command里,只要调用Webhook模型的任意方法(比如count()、first()),Artisan::output()就不再输出内容,也没有异常和日志报错。这个命令直接在bash里运行完全正常,其他涉及该Model的测试也没问题。

测试代码

<?php

namespace Tests\Unit\Console\Commands\Webhook\Customer;

use App\Models\Shopify\Webhook;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;

class ProcessUpdateWebhooksTest extends TestCase
{
    /** @test */
    public function thisWorksRightHere()
    {
        Artisan::call('boxer:process-customer-update-webhooks');

        $this->assertStringContainsString(
            'Hey',
            Artisan::output()
        );
    }
}

Command代码(注释Webhook::count()则测试通过,否则输出为空)

<?php

namespace App\Console\Commands\Webhook\Customer;

use App\Models\Shopify\Webhook;
use Illuminate\Console\Command;

class ProcessUpdateWebhooks extends Command
{
    protected $signature = 'boxer:process-customer-update-webhooks
        {--w|webhooks=25 : The maximum number of webhooks to process}';

    protected $description = 'Process orders/create webhooks from Shopify (default 25)';

    public function handle()
    {
        Webhook::count();
        $this->info('Hey');
    }
}

phpunit.xml相关配置

<php>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <!-- <env name="DB_DATABASE" value="testing"/> -->
        <env name="MAIL_MAILER" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="TELESCOPE_ENABLED" value="false"/>
    </php>

测试输出

PHPUnit 9.6.19 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 00:02.211, Memory: 48.50 MB

There was 1 failure:

1) Tests\Unit\Console\Commands\Webhook\Customer\ProcessUpdateWebhooksTest::thisWorksRightHere
Failed asserting that '' contains "Hey".

/Users/peterdemarco/code/projects/boxer/tests/Unit/Console/Commands/Webhook/Customer/ProcessUpdateWebhooksTest.php:16
/Users/peterdemarco/code/projects/boxer/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:61

排查方向

  • 测试数据库未初始化:你注释了DB_DATABASE配置,测试环境可能复用了生产数据库,或者测试数据库未创建/迁移。Webhook模型执行查询时可能触发未捕获的异常(比如数据库连接失败),导致命令提前退出,$this->info('Hey')根本没执行。可以在测试里手动捕获异常验证:
    try {
        Artisan::call('boxer:process-customer-update-webhooks');
    } catch (\Exception $e) {
        dd($e->getMessage());
    }
    
  • 模型全局作用域/观察者干扰:Webhook模型可能存在全局作用域或者观察者,在测试环境执行查询时抛出异常但未被捕获。可以临时注释模型里的全局作用域或观察者代码,看测试是否恢复正常。
  • 测试类初始化问题:确认测试类继承的TestCase是否正确处理了数据库初始化,比如setUp方法中是否运行了迁移,或者使用了数据库事务包裹测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:35:54