PhpSpec测试捕获异常



我有一个简单的测试:

function it_should_return_error_response_exception(Client $httpClient,CommandInterface $commandInterface)
{
    $httpClient->setDefaultOption('auth', array('api','api_pass', 'Basic'))
        ->shouldBeCalled();
    $httpClient->getCommand('search', array('api_key' => 'ehudwqukhjda'))
        ->shouldBeCalled()
        ->willReturn($commandInterface);
    $httpClient->execute($commandInterface)
        ->shouldBeCalled()
        ->willThrow(new BadResponseException('???', new Request('POST', 'http://vatteloapesca')));

    $this->shouldThrow('AcmeExceptionErrorResponseException')
        ->during('runCommand', array('search', array('api_key' => 'ehudwqukhjda')));
}

这是我想要的代码test:

  try{
        $result = $this->guzzleClient->execute($command);
    } catch (BadResponseException $e) {
        ErrorHandler::processError($e);
    }
    return $result;

错误处理程序类,它已经测试过,并将返回一个扩展'AcmeExceptionErrorResponseException'的类。问题是,如何模拟从guzzle客户端返回的异常??

我试过使用预言的willTrhow和ThrowPromises https://github.com/phpspec/prophecy

我的错误是什么?

我的意思是,用这个代码:

 $httpClient->execute($commandInterface)
        ->shouldBeCalled()
        ->willThrow(new BadResponseException('???', new Request('POST', 'http://vatteloapesca')));

'runCommand'(测试的函数)它将返回BadResponseException,但它没有被我的代码捕获。

你可以这样做:

在spec的顶部使用Exception:

use CRMPiccoBundleExceptionImageImportDirectoryUnavailableException;

$this->shouldThrow(ImageImportDirectoryUnavailableException::class)
->during('importImageAssets', [$imageImportPath]);

…并从你的代码中抛出它:

 public function importImageAssets($importDirectory)
 {
        $filesystem = new Filesystem();
        if (false === $filesystem->exists($importDirectory)) {
            throw new ImportDirectoryUnavailableException();
        }
        // ...
 }

相关内容

  • 没有找到相关文章

最新更新