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

能否在Pest PHP的beforeEach/beforeAll中传递变量至测试用例?

在Pest框架中共享beforeEach创建的$user变量给测试用例

完全可行,有两种常用实现方式:

方法一:使用测试实例的属性(推荐)

Pest的测试闭包默认绑定到测试类实例,你可以在beforeEach中将创建的用户赋值给$this->user,之后在任意测试用例里直接通过$this->user访问:

beforeEach(function () {
    $this->user = User::factory()->create();
});

test('Test that it shows finished tasks of company', function () {
    // 直接使用$this->user获取用户ID或其他属性
    $userId = $this->user->id;
    
    // 示例测试逻辑:模拟登录用户并请求接口
    $response = $this->actingAs($this->user)->get('/tasks/finished');
    
    $response->assertStatus(200);
    // 其他断言逻辑
});

方法二:通过闭包引用共享变量

如果不想使用$this,可以在闭包外部定义变量,然后通过use(&$user)的方式将变量引入beforeEach和测试用例的作用域中:

$user = null;

beforeEach(function () use (&$user) {
    $user = User::factory()->create();
});

test('Test that it shows finished tasks of company', function () use (&$user) {
    $userId = $user->id;
    // 测试逻辑
});

为什么Jest的方式在PHP中无效?

PHP的闭包作用域和JavaScript不同:Jest中beforeEach与测试用例共享同一个作用域,而PHP中每个闭包默认拥有独立作用域,必须通过use显式传递引用,或借助测试类实例的$this来共享变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:50:37