感谢你来到这里
                我真的很激动
                盼望,能有你的支持
            捐赠可扫描二维码转账支付
                 
                    支付宝扫一扫付款
 
                    微信扫一扫付款
(微信为保护隐私,不显示你的昵称)
强烈推荐在功能测试中只测试Response(对象)。但如果你写了用于监控生产环境服务器的功能测试,你也许要针对分析数据(profiling data)来编写测试,因为它给你提供了一个极佳方式来检查各种事项并强制(使用)了某些制式标准。
Symfony Profiler 对每一次请求收集大量数据。使用这个数据可以检查数据库查询次数,框架执行时间等等。但在编写断言(assertions)之前,需开启分析器并确保其可用 (它在 test environment 下是默认开启的):
| 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 | class LuckyControllerTest extends WebTestCase
{
    public function testNumberAction()
    {
        $client = static::createClient();
 
        // Enable the profiler for the next request
        // (it does nothing if the profiler is not available)
        // 在下一次请求中开启分析器(如果分析器不可用则什么也不做)
        $client->enableProfiler();
 
        $crawler = $client->request('GET', '/lucky/number');
 
        // ... write some assertions about the Response
        // ... 编写一些关于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 Profiler来分析请求。当你把token内嵌到错误信息中时,这很容易实现:
| 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()
    )
); | 
profiler store将根据环境(特别是当你使用SQLite store时,也就是默认的配置)而有所不同。
即便你隔离了客户端(client)或是对测试使用HTTP层(layer),分析信息仍然可用。
参考内置的 data collectors API以了解关于其接口的更多内容。
要避免在每次测试中收集信息,你可以设置 collect 参数为 false:
| 1 2 3 4 5 6 7 | # app/config/config_test.yml
 
# ...
framework:
    profiler:
        enabled: true
        collect: false | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
 
    <!-- ... -->
 
    <framework:config>
        <framework:profiler enabled="true" collect="false" />
    </framework:config>
</container> | 
这样一来,只有调用了 $client->enableProfiler() 的测试才会收集数据。
本文,包括例程代码在内,采用的是 Creative Commons BY-SA 3.0 创作共用授权。