【问题标题】:Symfony console command behat testSymfony 控制台命令 behat 测试
【发布时间】:2017-02-21 08:59:32
【问题描述】:

我有命令,这个命令连接到谷歌分析 API 并获取一些数据。这可行,但我尝试编写测试并且不知道如何模拟谷歌 API 连接。我的第一个想法是在上下文中模拟 google API,但如何将这个模拟注入命令?

/**
 * @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( ); $client->getContainer()->set('google.client_conversion.factory', YourFactoryClass);
  • 是的,你说得对。现在我正在开发类似的东西,但我用我想替换的模拟类创建了特殊的 service_test.yml: services: google.client_conversion.factory: class: ClientConversionFactoryMock arguments: ['%root_dir%/config/key/conversion_app.json']

标签: unit-testing symfony behat symfony-console


【解决方案1】:

我使用这样的东西:

    $client = static::createClient();

    $ldap = $this->getMockBuilder('AppBundle\Services\Security\LdapManager')
        ->disableOriginalConstructor()
        ->getMock();

    $client->getContainer()->set('app.ldap', $ldap);
    $crawler = $client->request('GET', '/');

【讨论】:

  • 哦,太好了,您刚刚从上面的评论中复制了我的答案,并给出了类似的解决方案。
猜你喜欢
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
  • 2017-11-02
相关资源
最近更新 更多