Aşağıdaki behat test aslında $this->mySpecialService->getAttachment($pathToAttachment); servisini çağırmayacak ama çağırmış gibi yapacak. Gerçek hayatta bazen API servislerini çağırmamız gerekebilir ama test ortamında bu tarz işlemler problem yaratabilirler. Bu nedenle biz bu testle servisi çağırıyormuşuz gibi yapıyoruz. Bu işlem için Symfony2 Mocker Extension kütüphanesini kullanıyoruz.


Kütüphaneyi yükleme


Composer.json


Composer.json dosyasına "polishsymfonycommunity/symfony2-mocker-extension": "*" satırını ekleyin ve composer update polishsymfonycommunity/symfony2-mocker-extension komutunu çalıştırın.


Behat.yml


default:
# ...
extensions:
PSS\Behat\Symfony2MockerExtension\Extension: ~

AppKernel.php


/**
* @return string
*/
protected function getContainerBaseClass()
{
if ('test' == $this->environment) {
return '\PSS\SymfonyMockerContainer\DependencyInjection\MockerContainer';
}

return parent::getContainerBaseClass();
}

Örnek controller


class MessageController extends AbstractController
{
/**
* @Method({"GET"})
* @Route("/orders/{orderId}/messages/{messageId}/attachments/{attachmentId}")
*
* @param int $orderId
* @param int $messageId
* @param int $attachmentId
*
* @return Response
*
* @throws HttpResponseException|NotFoundHttpException
*/
public function getMessageAttachmentAction($orderId, $messageId, $attachmentId)
{
try {
// Assuming that you did some work here

// Behat mocking mocks this part
$result = $this->mySpecialService->getAttachment($pathToAttachment);

if ($result->code != 200) {
throw new HttpResponseException(sprintf('Couldn\'t fetch image from [%s].', $pathToAttachment));
}

$response = new Response();
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', $attachmentContentType);
$response->headers->set('Content-Disposition', sprintf('attachment;filename=%s', $attachmentName));
$response->setStatusCode($result->code);
$response->sendHeaders();
$response->setContent($result->body);

return $response;
} catch (Exception $e) {
throw new NotFoundHttpException($e->getMessage());
}
}
}

Örnek senaryo


Feature: Just testing

Scenario: I can download specific message attachment
Given the Mailgun API is available
Then I send a GET request to "/api/orders/1/messages/1/attachments/1"
And the response status code should be 200

FeatureContext


use PSS\Behat\Symfony2MockerExtension\Context\ServiceMockerAwareInterface;
use PSS\Behat\Symfony2MockerExtension\ServiceMocker;

class FeatureContext extends MinkContext implements ServiceMockerAwareInterface
{
/**
* @var ServiceMocker
*/
private $mocker;

public function setServiceMocker(ServiceMocker $mocker)
{
$this->mocker = $mocker;
}

/**
* @Given /^the My special API is available$/
*/
public function mySpecialApiIsAvailable()
{
$response['body'] = 'Binary string goes here';
$response['code'] = 200;


// application_backend.service.my_special_api is defined in your service.yml
// Application\BackendBundle\Service\MySpecialApi is class that deals with API
// getAttachment() is defined in MySpecialApi class and gets triggered in controller
$this->mocker->mockService('application_backend.service.my_special_api', 'Application\BackendBundle\Service\MySpecialApi')
->shouldReceive('getAttachment')
->once()
->andReturn((object) $response);
}
}

Şu şekilde de yapabilirsiniz. Daha fazla bilgi için Mockery Docs'u ziyaret ediniz.


class Whatever
{
public function apiRequestResponseMock()
{
$mockResponse = Mockery::mock('Guzzle\Http\Message\Response');
$mockResponse->shouldReceive('getBody')->with(true)->andReturn('I am the response body');

$mockRequest = Mockery::mock('Guzzle\Http\Message\Request');
$mockRequest->shouldReceive('send');
$mockRequest->shouldReceive('getResponse')->andReturn($mockResponse);
}
}