跳到主要內容

如何在功能測試中使用效能分析器

編輯此頁面

強烈建議功能測試僅測試 Response。但是,如果您編寫功能測試來監控您的生產伺服器,您可能會想要對效能分析資料進行測試,因為它可以讓您很好地檢查各種事項並實施一些指標。

在測試中啟用效能分析器

使用 Symfony 效能分析器收集資料可能會顯著減慢您的測試速度。這就是 Symfony 預設停用它的原因

1
2
3
4
5
# config/packages/test/web_profiler.yaml

# ...
framework:
    profiler: { enabled: true, collect: false }

collect 設定為 true 會為所有測試啟用效能分析器。但是,如果您只需要在少數測試中使用效能分析器,您可以保持全域停用,並透過呼叫 $client->enableProfiler() 在每個測試中個別啟用效能分析器。

測試效能分析器資訊

Symfony 效能分析器收集的資料可用於檢查資料庫呼叫次數、框架中花費的時間等。所有這些資訊都由透過 $client->getProfile() 呼叫取得的收集器提供

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// tests/Controller/LuckyControllerTest.php
namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class LuckyControllerTest extends WebTestCase
{
    public function testRandomNumber(): void
    {
        $client = static::createClient();

        // enable the profiler only for the next request (if you make
        // new requests, you must call this method again)
        // (it does nothing if the profiler is not available)
        $client->enableProfiler();

        $crawler = $client->request('GET', '/lucky/number');

        // ... write some assertions about the Response

        // check that the profiler is enabled
        if ($profile = $client->getProfile()) {
            // check the number of requests
            $this->assertLessThan(
                10,
                $profile->getCollector('db')->getQueryCount()
            );

            // check the time spent in the framework
            $this->assertLessThan(
                500,
                $profile->getCollector('time')->getDuration()
            );
        }
    }
}

如果測試因效能分析資料而失敗(例如,資料庫查詢過多),您可能想要在測試完成後使用 Web 效能分析器來分析請求。這可以透過將權杖嵌入錯誤訊息中來實現

1
2
3
4
5
6
7
8
$this->assertLessThan(
    30,
    $profile->getCollector('db')->getQueryCount(),
    sprintf(
        'Checks that query count is less than 30 (token %s)',
        $profile->getToken()
    )
);

注意

即使您隔離用戶端或在測試中使用 HTTP 層,效能分析器資訊仍然可用。

提示

閱讀內建資料收集器的 API,以了解更多關於它們介面的資訊。

本作品,包括程式碼範例,以創用 CC BY-SA 3.0 授權條款授權。
目錄
    版本