Symfony 控制台命令 behat 测试

Symfony console command behat test

我有命令,此命令连接到 google 分析 API 并获取一些数据。这可行,但我尝试编写测试但不知道如何模拟 google 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 并在连接到特定事件调度程序的 google 服务时更改方法并模拟此事件。任何想法都会非常有帮助。

我用的是这样的:

    $client = static::createClient();

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

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