如何將函數從閉包轉移到普通函數
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 檔案底部的一個位置。