3

我有一个简单的测试:

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('Acme\Exception\ErrorResponseException')
        ->during('runCommand', array('search', array('api_key' => 'ehudwqukhjda')));
}

这是我要测试的代码:

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

已经测试过的错误处理程序类将返回一个扩展“Acme\Exception\ErrorResponseException”的类。问题是,如何从 guzzle 客户端模拟返回的异常?

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

我的错误是什么?

我的意思是,使用以下代码:

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

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

4

1 回答 1

2

你可以这样做:

使用规范顶部的异常:

use CRMPicco\Bundle\Exception\ImageImportDirectoryUnavailableException;

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

...并从您的代码中扔掉它:

 public function importImageAssets($importDirectory)
 {
        $filesystem = new Filesystem();

        if (false === $filesystem->exists($importDirectory)) {
            throw new ImportDirectoryUnavailableException();
        }

        // ...

 }
于 2016-03-03T16:11:38.260 回答