我想在测试时使用DoctrineDBALLoggingSQLLogger
检查我的查询时间。
Config/packages/test/doctrine.yaml中的配置:
doctrine:
dbal:
dbname_suffix: '_test%env(default::TEST_TOKEN)%'
logging: true
profiling: true
代码:
public function testSingleInsertTime()
{
$maxTimeInMs = 0.1; // Please ignore this and the fact that I'm testing single insert. Actual code is different.
$em = static::$entityManager;
$em->getConfiguration()->setSQLLogger(new DebugStack());
/** @var DebugStack */
$sqlLogger = $em->getConfiguration()->getSQLLogger();
$productState = (new ProductState())
->setId(123)
->setHash('EXP000276669cc123038419f265bf124')
;
$em->persist($productState);
$em->flush();
dump($sqlLogger->queries);die; // HERE i get an empty array :(
$actualTime = 1; // TODO: get from logger
$this->assertGreaterThan($maxTimeInMs, $actualTime);
}
在php bin/phpunit --filter testSingleInsertTime tests/Doctrine/ProductTest.php
之后,我在flush被调用后得到一个空数组。怎么了?
__
看,即使是简单的控制器与dev
环境失败!我的代码有问题。Sql日志记录器可能以另一种方式工作。
use DoctrineDBALLoggingDebugStack;
class DataDMLController extends AbstractController
{
/**
* @Route("/action", name="action")
*/
public function action(EntityManagerInterface $em)
{
$em->getConfiguration()->setSQLLogger(new DebugStack());
/** @var DebugStack */
$sqlLogger = $em->getConfiguration()->getSQLLogger();
$productState = (new ProductState())
->setId(124)
->setHash('EXP000276669cc123038419f265bf124')
;
$em->persist($productState);
$em->flush();
dump($sqlLogger->queries); // an empty array!
die;
return new Response();
}
}
解决方案是从连接(而不是直接从实体管理器)获取配置。
$em->getConnection()->getConfiguration()->setSQLLogger(new DebugStack());
我们必须理解,EntityManagerInterface有它自己的配置和连接也有它自己的,所以我们有2种不同的配置,我们必须设置sql记录器的连接是在DBAL组件和这样的组件管理执行查询。这不是实体管理器的角色,所以现在它是清晰易懂的。
__
选择
logging: true
profiling: true
不需要。