Unit testing Symfony控制台命令行为测试
我有一个命令,这个命令连接到google analytics API并获取一些数据。这是可行的,但我试图编写一个测试,不知道如何模拟GoogleAPI连接。我的第一个想法是在上下文中模拟GoogleAPI,但是如何将这个模拟注入到命令中呢Unit testing Symfony控制台命令行为测试,unit-testing,symfony,behat,symfony-console,Unit Testing,Symfony,Behat,Symfony Console,我有一个命令,这个命令连接到google analytics API并获取一些数据。这是可行的,但我试图编写一个测试,不知道如何模拟GoogleAPI连接。我的第一个想法是在上下文中模拟GoogleAPI,但是如何将这个模拟注入到命令中呢 /** * @inheritdoc * @param InputInterface $input * @param OutputInterface $output */ public function execute(InputInterface $i
/**
* @inheritdoc
* @param InputInterface $input
* @param OutputInterface $output
*/
public function execute(InputInterface $input, OutputInterface $output): void
{
//connect to google service
/** @var $googleClient \Google_Client*/
$googleClient = $this->googleConnect();
/** @var $shopTokenEntity TokenEntity */
foreach ($tokensDataProvider as $shopTokenEntity) {
//refresh token if necessary
$this->refreshToken($googleClient, $shopTokenEntity);
$clientGA = new AnalyticsConversion($googleClient);
/** @var $analytics \Google_Service_Analytics*/
$analytics = $clientGA->getAnalyticsService();
try {
//do some other staff get data and save to db
} catch (\Google_Service_Exception $err) {
$this->getLogger()->addWarning($err->getMessage());
}
}
}
/**
*
* @return \Google_Client
*/
private function googleConnect(): \Google_Client
{
/** @var $conversionApp ClientConversionFactory */
$conversionApp = $this->container->get('google.client_conversion.factory');
/** @var $googleClient \Google_Client */
$googleClient = $conversionApp->connect();
return $googleClient;
}
/**
* @param \Google_Client $googleClient
* @param TokenEntity $tokenEntity
*/
private function refreshToken(\Google_Client $googleClient, TokenEntity $tokenEntity): void
{
//set Auth
$googleClient->setAccessToken($tokenEntity->getAccessToken());
//refresh and save token if needed
if ($googleClient->isAccessTokenExpired()) {
$this->getLogger()->addInfo("Refresh token for ShopID: " . $tokenEntity->getShopId());
$googleClient->fetchAccessTokenWithRefreshToken();
//save token to db
}
}
我的第二个想法是添加EventListener,并在连接到google服务到特定事件调度器并模拟此事件时更改方法。任何想法都会很有帮助 我使用这样的东西:
$client = static::createClient();
$ldap = $this->getMockBuilder('AppBundle\Services\Security\LdapManager')
->disableOriginalConstructor()
->getMock();
$client->getContainer()->set('app.ldap', $ldap);
$crawler = $client->request('GET', '/');
若我理解正确,当您运行测试时,您可以访问它的容器,所以您可以尝试在测试中插入模拟类,例如:$client=static::createClient()$client->getContainer()->set('google.client\u conversion.factory',YourFactoryClass);是的,你是对的。现在我正在开发类似的东西,但我创建了特殊的服务\u test.yml,其中包含模拟类,我想替换为:services:google.client\u conversion.factory:class:ClientConversionFactoryMock参数:['%root\u dir%/config/key/conversion\u app.json'],这在将来会很有帮助。哦,太好了,你们只是从上面的评论中复制了我的答案,并给出了类似的解决方案。