3

I have a simple test:

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')));
}

And this one is the code that I want test:

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

The Error handler class it's already tested and will return a class that extends 'Acme\Exception\ErrorResponseException'. The question is, how to mocking a returning Exception from the guzzle Client??

I've tried to use the willTrhow and ThrowPromises of prophecy https://github.com/phpspec/prophecy

What's my error?

I mean, with this code:

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

'runCommand' ( the function tested) it will return the BadResponseException but it's not catched by my code.

erlangb
  • 521
  • 6
  • 13

1 Answers1

2

You could do something like this:

Use the Exception at the top of your spec:

use CRMPicco\Bundle\Exception\ImageImportDirectoryUnavailableException;

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

...and throwing it from you code:

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

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

        // ...

 }
crmpicco
  • 16,605
  • 26
  • 134
  • 210