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

如何在Laravel中使用Pest测试Sentry的captureException方法是否被调用?

使用PHPUnit测试Sentry captureException调用

核心思路是模拟Sentry实例、满足生产环境条件,然后触发异常验证方法调用:

  1. 模拟Sentry客户端并绑定到Laravel容器,确保app()->bound('sentry')返回true
  2. 临时将环境设置为production,匹配原代码的判断条件
  3. 抛出测试异常触发报告逻辑,最后断言方法调用情况

代码示例:

use Illuminate\Foundation\Testing\TestCase;
use Sentry\ClientInterface;
use Throwable;

class ExceptionReportingTest extends TestCase
{
    public function test_sentry_captures_exception_in_production()
    {
        // 创建Sentry客户端模拟对象
        $sentryMock = $this->createMock(ClientInterface::class);
        
        // 绑定到容器
        $this->app->instance('sentry', $sentryMock);
        
        // 设置生产环境
        config()->set('app.env', 'production');
        
        // 断言captureException被调用一次,且传入Throwable实例
        $sentryMock->expects($this->once())
            ->method('captureException')
            ->with($this->isInstanceOf(Throwable::class));
        
        // 抛出异常触发报告逻辑
        throw new \Exception('Test exception');
    }
}
使用Pest测试Sentry captureException调用

Pest基于PHPUnit,语法更简洁,流程和PHPUnit一致:

代码示例:

use Sentry\ClientInterface;

it('captures exception with Sentry in production environment', function () {
    // 模拟Sentry客户端
    $sentryMock = mock(ClientInterface::class);
    
    // 绑定到容器
    app()->instance('sentry', $sentryMock);
    
    // 设置生产环境
    config()->set('app.env', 'production');
    
    // 预期captureException被调用一次
    $sentryMock->shouldReceive('captureException')
        ->once()
        ->withArgs(fn ($e) => $e instanceof Throwable);
    
    // 抛出异常触发逻辑
    throw new Exception('Test exception');
});

额外场景测试:非生产环境不调用

可以补充验证非生产环境下逻辑不执行:

it('does not capture exception with Sentry in non-production environment', function () {
    $sentryMock = mock(ClientInterface::class);
    app()->instance('sentry', $sentryMock);
    
    config()->set('app.env', 'local');
    
    // 断言captureException完全不被调用
    $sentryMock->shouldNotReceive('captureException');
    
    throw new Exception('Test exception');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:22:47