Symfony测试中Profiler数据库查询计数始终为0的问题
问题排查:Symfony测试中DB Profiler返回查询数为0
可能的原因及解决方案
1. 重复调用enableProfiler()导致数据丢失
你的测试代码在请求前后各调用了一次$this->client->enableProfiler();,仅需在发起请求前调用一次即可。第二次调用会重置Profiler状态,导致无法收集请求过程中的查询数据:
public function testRandomNumber(): void { // 仅在请求前启用一次Profiler $this->client->enableProfiler(); $this->client->request( Request::METHOD_GET, '/api/myRoute/find' ); self::assertResponseStatusCodeSame(Response::HTTP_OK); if ($profile = $this->client->getProfile()) { $count = $profile->getCollector('db')->getQueryCount(); $this->assertLessThan(10, $count); } }
2. 测试环境Doctrine查询日志未启用
即使Profiler开启,若Doctrine未启用查询日志,DB Collector也无法收集数据。需在config/packages/test/doctrine.yaml中明确配置:
doctrine: dbal: # 保留原有DB连接配置 logging: true orm: # 保留原有ORM配置 auto_generate_proxy_classes: true query_cache_driver: { type: array } metadata_cache_driver: { type: array } result_cache_driver: { type: array }
3. 提前获取EntityManager导致Profiler未拦截
你在setUp()中提前获取了EntityManager,但此时Profiler尚未启用(enableProfiler()在测试方法中才调用)。该EntityManager实例未被Profiler监听包裹,其执行的查询不会被统计。
若测试需使用EntityManager,应在启用Profiler之后获取:
public function testRandomNumber(): void { $this->client->enableProfiler(); // 启用Profiler后再获取EntityManager $this->em = $this->client->getContainer()->get('doctrine')->getManager(); $this->client->request(Request::METHOD_GET, '/api/myRoute/find'); self::assertResponseStatusCodeSame(Response::HTTP_OK); if ($profile = $this->client->getProfile()) { $count = $profile->getCollector('db')->getQueryCount(); $this->assertLessThan(10, $count); } }
4. 确认接口确实执行了数据库查询
先手动调用/api/myRoute/find接口,查看Web Profiler工具栏的DB查询数,确认接口本身存在数据库操作。若接口从缓存(如Redis、Doctrine缓存)返回数据,查询数自然为0。
额外验证步骤
- 打印
$profile->getCollector('db')->getQueries()查看具体查询列表,确认是否有数据。 - 检查
var/log/test.log是否存在Profiler相关错误,排除配置加载问题。
内容的提问来源于stack exchange,提问作者pop_up
相关产品推荐
相关产品推荐

