如何将函数从闭包转移到普通函数
P粉831310404
2023-09-05 21:54:44
<p>我正在尝试使害虫测试文件更易于阅读。</p>
<p>目前,我有一些标准测试:</p>
<pre class="brush:php;toolbar:false;">test('can get subscribers latest subscription', function () {
$this->seed(PlansTestSeeder::class);
$this->seed(SubscriptionsTestSeeder::class);
$this->assertDatabaseCount('plans', 2);
$this->assertDatabaseCount('subscriptions', 0);
Subscription::factory()->create([
"plan_id" => Plan::where("slug", "bronze")->first()->id
]);
Subscription::factory()->create([
"plan_id" => Plan::where("slug", "silver")->first()->id
]);
Subscription::factory()->create([
"plan_id" => Plan::where("slug", "silver")->first()->id,
"status" => "expired"
]);
Subscription::factory()->trashed()->create();
$this->assertDatabaseCount('subscriptions', 4);
});
test('can get subscribers active subscriptions', function () {
$this->seed(PlansTestSeeder::class);
$this->seed(SubscriptionsTestSeeder::class);
$silverPlan = Plan::where("slug", "silver")->first();
$subscription1 = Subscription::factory()->create([
"plan_id" => Plan::where("slug", "silver")->first()->id,
"subscriber_id" => 1,
"subscriber_type" => "ApresourcingFramework\Billing\Tests\Models\Subscriber",
"created_at" => now()->subDays(2),
"started_at" => now()->subDays(2)
]);
$subscription2 = Subscription::factory()->create([
"plan_id" => $silverPlan->id,
"subscriber_id" => 1,
"subscriber_type" => "ApresourcingFramework\Billing\Tests\Models\Subscriber",
"created_at" => now()->subDays(1),
"started_at" => now()->subDays(1)
]);
$user = Subscriber::find(1);
$subscription = $user->latestSubscription();
expect($subscription->id)->toBe($subscription2->id);
});</pre>
<p>但是为了提醒自己我编写了哪些测试,我必须一遍又一遍地上下滚动页面。</p>
<p>我想做的是更改为如下内容:</p>
<pre class="brush:php;toolbar:false;">test('can get subscribers latest subscription', getLatestSubscription());
test('can get subscribers active subscriptions', getActiveSubscriptions());
function getLatestSubscription() {
/// function code here
});
function getActiveSubscriptions() {
// function code here
});</pre>
<p>但是,测试函数包含对 $this 的引用,它在正常闭包中可用,但在标准函数中不可用,因为我在此处设置了它。</p>
<p>编辑:我正在使用 laravel pest 插件 - 我不确定这是否会对 $this 的使用产生影响</p>
<p>有什么办法可以解决这个问题吗?</p>
感谢回复中的一些提示。不像我希望的那样整洁,但至少这意味着所有测试(“测试描述”)调用都位于 php 文件底部的一个位置。