Symfony控制台命令behat测试
问题描述:
我有命令和此命令连接到谷歌分析API并获取一些数据。这工作,但我尝试写一个测试,不知道如何模拟谷歌API连接。我的第一个想法是在上下文中模拟Google API,但是如何将此模拟注入命令?Symfony控制台命令behat测试
/**
* @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和更改方法,当我连接到谷歌服务特定的事件调度和模拟此事件。任何想法都会非常有帮助。
答
我用成才这样的:
$client = static::createClient();
$ldap = $this->getMockBuilder('AppBundle\Services\Security\LdapManager')
->disableOriginalConstructor()
->getMock();
$client->getContainer()->set('app.ldap', $ldap);
$crawler = $client->request('GET', '/');
+0
哦,太棒了,你刚刚从上面的评论复制我的答案,并给它像解决方案。 –
如果我理解正确的话,当你运行你的测试,您可以访问它的容器,所以你可以尝试插入你的模拟类的测试,例如: $ client = static :: createClient(); $ client-> getContainer() - > set('google.client_conversion.factory',YourFactoryClass); –
是的,你有权利。现在我正在开发类似的东西,但我创建了特殊的service_test.yml与我想替换的模拟类: 服务: google.client_conversion.factory: class:ClientConversionFactoryMock 参数:['%root_dir%/ config/key/conversion_app .json'] –
[在symfony中用behat嘲笑外部API](http://www.inanzzz.com/index.php/post/2blk/mocking-external-apis-with-behat-in-symfony)和[Mocking内部或外部服务或api电话与behat](http://www.inanzzz.com/index.php/post/2y8u/mocking-internal-or-external-service-or-api-calls-with-behat)会在未来会有所帮助。 – BentCoder