跳到内容

如何在功能测试中使用分析器

编辑此页

强烈建议功能测试仅测试响应(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()
            );
        }
    }
}

如果测试因分析数据(例如,DB 查询过多)而失败,您可能希望在测试完成后使用 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,以了解有关其接口的更多信息。

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本