Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SymfonyCon Madrid 2014 - PHP object mocking framework world

Sarah KHALIL
November 27, 2014
1.3k

SymfonyCon Madrid 2014 - PHP object mocking framework world

Heard about PHPSpec? Well its PHP object mocking framework called Prophecy is quite nice. We'll discover its API, similarities and improvements regarding the one from PHPUnit. Finally, we'll take a look at the integration of Prophecy in PHPUnit.

Sarah KHALIL

November 27, 2014
Tweet

Transcript

  1. PHP OBJECT MOCKING FRAMEWORK WORLD

    LET'S COMPARE PROPHECY AND PHPUNIT
    Sarah Khalil - @saro0h

    View full-size slide

  2. TODAY, HOPEFULLY, WE LEARN NEW
    THINGS
    1. Terminology about objects doubling

    2. PHPUnit implementation

    3. Prophecy implementation

    4. The differences between the two philosophies

    View full-size slide

  3. Dummies are objects that are passed
    around but never used. They are usually
    used to fill a list of parameters.

    View full-size slide

  4. Stubs are objects that implement the
    same methods than the real object.
    These methods do nothing and are
    configured to return a specific value.

    View full-size slide

  5. Mocks are pre-programmed with expectations
    which form a specification of the calls they are
    expected to receive. They can throw an exception if
    they receive a call they don't expect and are
    checked during verification to ensure they got all
    the calls they were expecting.

    View full-size slide

  6. PHPUNIT MOCKING LIBRARY

    View full-size slide

  7. FUNDAMENTALS

    View full-size slide

  8. Your test class must extend

    PHPUnit_Framework_TestCase

    View full-size slide

  9. The method you need to know

    $this->getMock()

    View full-size slide

  10. • Generates an object

    • All methods return NULL

    • You can describe the
    expected behavior of your
    object

    View full-size slide

  11. DUMMY
    $dummy = $this->getMock('Namespace');

    View full-size slide

  12. STUB
    $event = $this->getMock(‘Symfony\Component\HttpKernel\Event
    \GetResponseEvent’);
    !
    $event
    ->method('getRequest')
    ->will($this->returnValue($this->request))
    ;

    View full-size slide

  13. MOCK
    $dispatcher = $this->getMock(‘Symfony\Component
    \EventDispatcher\EventDispatcherInterface');
    !
    $dispatcher
    ->expects($this->once())
    ->method(‘dispatch')
    ->with(
    $this->equalTo(SecurityEvents::INTERACTIVE_LOGIN),
    $this->equalTo($loginEvent)
    )
    ;

    View full-size slide

  14. REAL LIFE EXAMPLE

    View full-size slide

  15. Who knows exactly how the
    Oauth dance of Github works?
    Don’t worry, we don’t care!

    View full-size slide

  16. THE ORIGINAL CODE

    View full-size slide

  17. namespace PoleDev\AppBundle\Security;!
    !
    use Guzzle\Service\Client;!
    use Psr\Log\LoggerInterface;!
    use Symfony\[…]\Router;!
    use Symfony\[…]\Response;!
    use Symfony\[…]\Request;!
    use Symfony\[…]\SimplePreAuthenticatorInterface;!
    use Symfony\[…]\AuthenticationFailureHandlerInterface;!
    use Symfony\[…]\TokenInterface;!
    use Symfony\[…]\UserProviderInterface;!
    use Symfony\[…]\AuthenticationException;!
    use Symfony\[…]\UrlGeneratorInterface;!
    use Symfony\[…]\HttpException;!
    use Symfony\[…]\PreAuthenticatedToken;!
    !
    class GithubAuthenticator implements
    SimplePreAuthenticatorInterface,
    AuthenticationFailureHandlerInterface!
    {!
    ! // Some code…!
    }

    View full-size slide

  18. private $client;
    private $router;
    private $logger;
    !
    public function __construct(
    Client $client,
    Router $router,
    LoggerInterface $logger,
    $clientId,
    $clientSecret
    )
    {
    $this->client = $client;
    $this->router = $router;
    $this->logger = $logger;
    $this->clientId = $clientId;
    $this->clientSecret = $clientSecret;
    }

    View full-size slide

  19. function createToken(Request $request, $providerKey)
    {
    $request = $this->client->post(…);
    $response = $request->send();
    $data = $response->json();
    !
    if (isset($data['error'])) {
    $message = ‘An error occured…’;
    $this->logger->notice($message);
    throw new HttpException(401, $message);
    }
    !
    return new PreAuthenticatedToken(
    ‘anon.',
    $data[‘access_token'],
    $providerKey
    );
    }

    View full-size slide

  20. STEP 1: GET ACCESS TOKEN
    $url = $this->router->generate(‘admin’,[], true);
    $endpoint = ‘/login/oauth/access_token’;
    !
    $request = $this->client->post($endpoint,[], [
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $url
    ]);
    !
    $response = $request->send();
    $data = $response->json();

    View full-size slide

  21. STEP 2: IF ERROR FROM GITHUB, EXCEPTION
    if (isset($data['error'])) {
    $message = 'An error occured during authentication with Github.';
    $this->logger->notice($message, [
    'HTTP_CODE_STATUS' => 401,
    ‘error' => $data['error'],
    'error_description' => $data['error_description'],
    ]);
    !
    throw new HttpException(401, $message);
    }

    View full-size slide

  22. STEP 3: CREATE TOKEN
    return new PreAuthenticatedToken(
    'anon.',
    $data[‘access_token’],
    $providerKey
    );

    View full-size slide

  23. LET’S TEST IT!

    View full-size slide

  24. WHAT TO TEST?

    View full-size slide

  25. public function createToken(Request $request, $providerKey)
    {
    $request = $this->client->post('/login/oauth/access_token', array(), array (
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $this->router->generate('admin', array(), UrlGeneratorInterface::ABSOLUTE_URL)
    ));
    !
    $response = $request->send();
    !
    $data = $response->json();
    !
    if (isset($data['error'])) {
    $message = sprintf('An error occured during authentication with Github. (%s)',
    $data['error_description']);
    $this->logger->notice(
    $message,
    array(
    'HTTP_CODE_STATUS' => Response::HTTP_UNAUTHORIZED,
    'error' => $data['error'],
    'error_description' => $data['error_description'],
    )
    );
    !
    throw new HttpException(Response::HTTP_UNAUTHORIZED, $message);
    }
    !
    return new PreAuthenticatedToken(
    ‘anon.',
    $data[‘access_token'],
    $providerKey
    );
    }
    We need to test
    the result of this
    method

    View full-size slide

  26. CREATE THE TEST CLASS

    View full-size slide

  27. namespace PoleDev\AppBundle\Tests\Security;
    !
    class GithubAuthenticatorTest extends \PHPUnit_Framework_TestCase
    {
    public function testCreateToken()
    {
    }
    }

    View full-size slide

  28. LET’S CALL THE CODE WE
    NEED TO TEST

    View full-size slide

  29. LET’S GET OUR DUMMIES AND CALL OUR METHOD TO TEST
    public function testCreateToken()
    {
    $githubAuthenticator = new GithubAuthenticator(
    $client,
    $router,
    $logger,
    '',
    ''
    );
    !
    $token = $githubAuthenticator
    ->createToken($request, ‘secure_area')
    ;
    }

    View full-size slide

  30. To construct the
    GithubAuthenticator, we need:

    • Guzzle\Service\Client
    • Symfony\Bundle\FrameworkBundle\Routing\Router
    • Psr\Log\LoggerInterface
    • $clientId = ‘’
    • $clientSecret = ‘’

    View full-size slide

  31. To call the createToken()
    method, we need

    !
    • Symfony\Component\HttpFoundation\Request
    • $providerKey = 'secure_area'

    View full-size slide

  32. $client = $this->getMock(‘Guzzle\Service
    \Client’);
    !
    $router = $this->getMock('Symfony\Bundle
    \FrameworkBundle\Routing\Router');
    !
    $logger = $this->getMock('Psr\Log
    \LoggerInterface');
    !
    $request = $this->getMock('Symfony\Component
    \HttpFoundation\Request');
    This a dummy

    View full-size slide

  33. We must disable the use of
    the original Router
    constructor as we don’t
    actually care.

    View full-size slide

  34. $router = $this->getMockBuilder('Symfony
    \Bundle\FrameworkBundle\Routing\Router')
    ->disableOriginalConstructor()
    ->getMock()
    ;

    View full-size slide

  35. MacBook-Pro-de-Sarah:~/Documents/talks/
    symfonycon-madrid-2014/code-exemple$ phpunit -
    c app/ src/PoleDev/AppBundle/Tests/Security/
    GithubAuthenticatorTest.php !
    !
    PHPUnit 4.3.5 by Sebastian Bergmann.!
    Configuration read from /Users/saro0h/
    Documents/talks/symfonycon-madrid-2014/code-
    exemple/app/phpunit.xml.dist!
    !
    PHP Fatal error: Call to a member function
    send() on null in /Users/saro0h/Documents/
    talks/symfonycon-madrid-2014/code-exemple/src/
    PoleDev/AppBundle/Security/
    GithubAuthenticator.php on line 43

    View full-size slide

  36. STEP 1: GET ACCESS TOKEN
    $url = $this->router->generate(‘admin’,[], true);
    $endpoint = ‘/login/oauth/access_token’;
    !
    $request = $this->client->post($endpoint,[], [
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $url
    ]);
    !
    $response = $request->send();
    $data = $response->json();

    View full-size slide

  37. 1/ We need to stub the
    call to the method
    $router->generate()
    it needs to return an url

    View full-size slide

  38. !
    !
    $router->method('generate')!
    ->with('admin',[], true)!
    ->willReturn(‘http://domain.name')!
    ;!

    View full-size slide

  39. 2/ We need to create a dummy
    Guzzle\Http\Message
    \EntityEnclosingRequest
    $guzzleRequest

    View full-size slide

  40. $guzzleRequest = $this!
    ! ! ->getMockBuilder('Guzzle\Http
    \Message\EntityEnclosingRequest')!
    ->disableOriginalConstructor()!
    ->getMock()!
    ;

    View full-size slide

  41. 3/ We need to stub the call to
    the method $client-
    >post(), it needs to return a
    $guzzleRequest

    View full-size slide

  42. $endpoint = '/login/oauth/access_token';!
    !
    $client->method('post')!
    ->with($endpoint, [], [!
    'client_id' => '',!
    'client_secret' => '',!
    'code' => '',!
    'redirect_uri' => 'http://domain.name'!
    ])!
    ->willReturn($guzzleRequest)!
    ;

    View full-size slide

  43. ORIGINAL CODE (STEP 1: GET ACCESS TOKEN)
    $url = $this->router->generate(‘admin’,[], true);
    $endpoint = ‘/login/oauth/access_token’;
    !
    $request = $this->client->post($endpoint,[], [
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $url
    ]);
    !
    $response = $request->send();
    $data = $response->json();

    View full-size slide

  44. Create a stub for $request->send()

    This method must return a:

    Guzzle\Http\Message\Response $response
    !
    Let’s go for it!

    View full-size slide

  45. $guzzleResponse = $this->getMockBuilder('Guzzle\Http
    \Message\Response')
    ->disableOriginalConstructor()
    ->getMock()
    ;
    !
    $guzzleRequest
    ->method(‘send')
    ->willReturn($guzzleResponse)
    ;

    View full-size slide

  46. Hurray! The original code is
    running with our dummies and
    stubs.

    But we do not test anything.

    View full-size slide

  47. A LITTLE REMINDER

    View full-size slide

  48. public function createToken(Request $request, $providerKey)
    {
    $request = $this->client->post('/login/oauth/access_token', array(), array (
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $this->router->generate('admin', array(), UrlGeneratorInterface::ABSOLUTE_URL)
    ));
    !
    $response = $request->send();
    !
    $data = $response->json();
    !
    if (isset($data['error'])) {
    $message = sprintf('An error occured during authentication with Github. (%s)',
    $data['error_description']);
    $this->logger->notice(
    $message,
    array(
    'HTTP_CODE_STATUS' => Response::HTTP_UNAUTHORIZED,
    'error' => $data['error'],
    'error_description' => $data['error_description'],
    )
    );
    !
    throw new HttpException(Response::HTTP_UNAUTHORIZED, $message);
    }
    !
    return new PreAuthenticatedToken(
    ‘anon.',
    $data[‘access_token'],
    $providerKey
    );
    }
    We need to test
    the result of this
    method

    View full-size slide

  49. TEST THAT THE TOKEN IS WHAT WE NEED TO BE
    $token = $githubAuthenticator->createToken($request, ‘secure_area’);!
    !
    $this->assertSame('a_fake_access_token', $token->getCredentials());!
    $this->assertSame('secure_area', $token->getProviderKey());!
    $this->assertSame('anon.', $token->getUser());!
    $this->assertEmpty($token->getRoles());!
    $this->assertFalse($token->isAuthenticated());!
    $this->assertEmpty($token->getAttributes());!
    !

    View full-size slide

  50. Duck! Our token has its credentials at null.

    You need to provide it as the real code would have done it.

    !
    Github returns an access token at that point.

    View full-size slide

  51. $guzzleResponse!
    ->method('json')!
    ->willReturn([!
    ‘access_token' => !
    ‘a_fake_access_token’!
    ])!
    ;

    View full-size slide

  52. Hurray! The original code is running
    with our dummies and stubs.

    And it is tested !

    View full-size slide

  53. USING A MOCK THIS TIME
    $guzzleResponse!
    ->expects($this->once())!
    ->method('json')!
    ->willReturn([!
    ‘access_token' => ‘a_fake_access_token'!
    ])!
    ;
    Expectation create a new assertion.

    View full-size slide

  54. FUNDAMENTALS

    View full-size slide

  55. PROPHET
    $prophet = new \Prophecy\Prophet;

    View full-size slide

  56. DUMMY
    $routerObjectProphecy = $prophet
    ->prophesize(‘Symfony\Bundle\FrameworkBundle\Routing\Router')
    ;
    !
    $router = $routerObjectProphecy->reveal();
    dummy

    View full-size slide

  57. PROPHECY
    • Object used to describe the
    future of your objects.

    !
    $prophecy = $prophet->prophesize(‘YourClass’);

    View full-size slide

  58. Note that the prophet won’t use the
    original constructor.

    View full-size slide

  59. OBJECT DOUBLE
    The goal is to get the object double

    !
    $prophecy->reveal();

    View full-size slide

  60. STUB 1/2
    • Get a stub out from the
    Router of Symfony.

    • $router->generate() must
    return http://www.google.com

    View full-size slide

  61. STUB 2/2
    $prophecy
    ->generate(‘route_name’)
    ->willReturn(‘http://www.google.com’)
    ;

    View full-size slide

  62. • willReturn() => is actually
    a promise.

    View full-size slide

  63. A promise is a piece of code
    allowing that a method call with a
    certain argument (if there is one),
    returns always the same value.

    View full-size slide

  64. $prophecy->willReturn(‘my value’); Returns the value ‘my value’.
    $prophecy->willReturnArgument(); Returns the first method argument.
    $prophecy->willThrow(‘ExceptionClass’); Throws an exception.
    !
    !
    $prophecy->will($callback)
    !
    $prophecy->will(new Prophecy\Promise
    \ReturnPromise(array(‘my value’));
    ===
    $prophecy->willReturn(‘my value’);
    PROMISE - API
    https://github.com/phpspec/prophecy/blob/master/src/Prophecy/Prophecy/MethodProphecy.php
    Details about the implementation:

    View full-size slide

  65. NOT ENOUGH?
    Implement the

    Prophecy\Promise\PromiseInterface

    View full-size slide

  66. HARD CODED ARGUMENT
    $prophecy
    ->generate(‘route_name’)
    ->willReturn(‘http://www.google.com’)
    ;

    View full-size slide

  67. NO HARD CODE
    • Prophecy offers you plenty of methods
    to « wildcard » the arguments

    • Any argument is ok for the method
    you are « stubbing »

    Prophecy\Argument::any()

    View full-size slide

  68. $prophecy
    ->myMethod(Prophecy\Argument::any())
    ;

    View full-size slide

  69. ARGUMENT THE API
    • Pretty complete

    • To go further with this

    https://github.com/phpspec/prophecy#arguments-wildcarding
    =>

    View full-size slide

  70. ADD EXPECTATIONS
    $prophecy
    ->generate(‘route_name’)
    ->willReturn(‘http://www.google.com’)
    ->shouldBeCalled()
    ;

    View full-size slide

  71. We expect to have that method
    generate() called at least one
    time.

    How we call it in real life ?
    Predictions!

    View full-size slide

  72. PREDICTIONS API
    ShouldBeCalled()
    shouldNotBeCalled()
    shouldBeCalledTimes(2)

    View full-size slide

  73. NOT ENOUGH?
    Implement the

    Prediction\PredictionInterface

    View full-size slide

  74. $prophet->checkPredictions();
    !
    (in your tearDown()
    method to check
    for all tests)

    View full-size slide

  75. If the prediction fails, it
    throws an exception.

    View full-size slide

  76. Verifies that a method has been
    called during the execution

    !
    $em = $prophet->prophesize('Doctrine\ORM\EntityManager');
    !
    $controller->createUser($em->reveal());
    !
    $em->flush()->shouldHaveBeenCalled();
    Exemple taken from the official prophecy repository

    View full-size slide

  77. REAL LIFE EXAMPLE

    View full-size slide

  78. THE ORIGINAL CODE
    You don’t remember
    right…

    View full-size slide

  79. namespace PoleDev\AppBundle\Security;!
    !
    use Guzzle\Service\Client;!
    use Psr\Log\LoggerInterface;!
    use Symfony\[…]\Router;!
    use Symfony\[…]\Response;!
    use Symfony\[…]\Request;!
    use Symfony\[…]\SimplePreAuthenticatorInterface;!
    use Symfony\[…]\AuthenticationFailureHandlerInterface;!
    use Symfony\[…]\TokenInterface;!
    use Symfony\[…]\UserProviderInterface;!
    use Symfony\[…]\AuthenticationException;!
    use Symfony\[…]\UrlGeneratorInterface;!
    use Symfony\[…]\HttpException;!
    use Symfony\[…]\PreAuthenticatedToken;!
    !
    class GithubAuthenticator implements
    SimplePreAuthenticatorInterface,
    AuthenticationFailureHandlerInterface!
    {!
    ! // Some code…!
    }

    View full-size slide

  80. private $client;
    private $router;
    private $logger;
    !
    public function __construct(
    Client $client,
    Router $router,
    LoggerInterface $logger,
    $clientId,
    $clientSecret
    )
    {
    $this->client = $client;
    $this->router = $router;
    $this->logger = $logger;
    $this->clientId = $clientId;
    $this->clientSecret = $clientSecret;
    }

    View full-size slide

  81. function createToken(Request $request, $providerKey)
    {
    $request = $this->client->post(…);
    $response = $request->send();
    $data = $response->json();
    !
    if (isset($data['error'])) {
    $message = ‘An error occured…’;
    $this->logger->notice($message);
    throw new HttpException(401, $message);
    }
    !
    return new PreAuthenticatedToken(
    ‘anon.',
    $data[‘access_token'],
    $providerKey
    );
    }

    View full-size slide

  82. STEP 1: GET ACCESS TOKEN
    $url = $this->router->generate(‘admin’,[], true);
    $endpoint = ‘/login/oauth/access_token’;
    !
    $request = $this->client->post($endpoint,[], [
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $url
    ]);
    !
    $response = $request->send();
    $data = $response->json();

    View full-size slide

  83. STEP 2: IF ERROR FROM GITHUB, EXCEPTION
    if (isset($data['error'])) {
    $message = 'An error occured during authentication with Github.';
    $this->logger->notice($message, [
    'HTTP_CODE_STATUS' => 401,
    ‘error' => $data['error'],
    'error_description' => $data['error_description'],
    ]);
    !
    throw new HttpException(401, $message);
    }

    View full-size slide

  84. STEP 3: CREATE TOKEN
    return new PreAuthenticatedToken(
    'anon.',
    $data[‘access_token’],
    $providerKey
    );

    View full-size slide

  85. LET’S TEST IT!
    AGAIN !

    View full-size slide

  86. WHAT TO TEST?

    View full-size slide

  87. public function createToken(Request $request, $providerKey)
    {
    $request = $this->client->post('/login/oauth/access_token', array(), array (
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $this->router->generate('admin', array(), UrlGeneratorInterface::ABSOLUTE_URL)
    ));
    !
    $response = $request->send();
    !
    $data = $response->json();
    !
    if (isset($data['error'])) {
    $message = sprintf('An error occured during authentication with Github. (%s)',
    $data['error_description']);
    $this->logger->notice(
    $message,
    array(
    'HTTP_CODE_STATUS' => Response::HTTP_UNAUTHORIZED,
    'error' => $data['error'],
    'error_description' => $data['error_description'],
    )
    );
    !
    throw new HttpException(Response::HTTP_UNAUTHORIZED, $message);
    }
    !
    return new PreAuthenticatedToken(
    ‘anon.',
    $data[‘access_token'],
    $providerKey
    );
    }
    We need to test
    the result of this
    method

    View full-size slide

  88. CREATE THE TEST CLASS

    View full-size slide

  89. namespace PoleDev\AppBundle\Tests\Security;
    !
    class GithubAuthenticatorTest extends \PHPUnit_Framework_TestCase
    {
    public function testCreateToken()
    {
    }
    }

    View full-size slide

  90. FIRST, GET THE PROPHET
    namespace PoleDev\AppBundle\Tests\Security;
    !
    class GithubAuthenticatorTest extends \PHPUnit_Framework_TestCase
    {
    private $prophet;
    !
    public function testCreateToken()
    {
    }
    !
    public function setUp()
    {
    $this->prophet = new \Prophecy\Prophet;
    }
    !
    public function tearDown()
    {
    $this->prophet = null;
    }
    }

    View full-size slide

  91. LET’S GET OUR DUMMIES AND CALL OUR METHOD TO TEST
    public function testCreateToken()
    {
    $githubAuthenticator = new GithubAuthenticator(
    $client,
    $router,
    $logger,
    '',
    ''
    );
    !
    $token = $githubAuthenticator
    ->createToken($request, ‘secure_area')
    ;
    }

    View full-size slide

  92. To construct the
    GithubAuthenticator, we need

    • Guzzle\Service\Client
    • Symfony\Bundle\FrameworkBundle\Routing\Router
    • Psr\Log\LoggerInterface
    • $clientId = ‘’
    • $clientSecret = ‘’

    View full-size slide

  93. To call the createToken()
    method, we need

    !
    • Symfony\Component\HttpFoundation\Request
    • $providerKey = 'secure_area'

    View full-size slide

  94. LET’S GET OUR DUMMIES AND CALL
    OUR METHOD TO TEST
    public function testCreateToken()
    {
    $clientObjectProphecy = $this->prophet->prophesize('Guzzle\Service\Client');
    $client = $clientObjectProphecy->reveal();
    !
    // …
    }
    This a prophecy
    This a dummy

    View full-size slide

  95. $routerObjectProphecy = $this->prophet
    ->prophesize('Symfony\Bundle\FrameworkBundle
    \Routing\Router');
    $router = $routerObjectProphecy->reveal();
    !
    $loggerObjectProphecy = $this->prophet
    ->prophesize('Psr\Log\LoggerInterface');
    $logger = $loggerObjectProphecy->reveal();
    !
    $requestObjectProphecy = $this->prophet
    ->prophesize('Symfony\Component\HttpFoundation
    \Request');
    $request = $requestObjectProphecy->reveal();

    View full-size slide

  96. MacBook-Pro-de-Sarah:~/Documents/talks/
    symfonycon-madrid-2014/code-exemple$ phpunit -
    c app/ src/PoleDev/AppBundle/Tests/Security/
    GithubAuthenticatorTest.php !
    !
    PHPUnit 4.3.5 by Sebastian Bergmann.!
    Configuration read from /Users/saro0h/
    Documents/talks/symfonycon-madrid-2014/code-
    exemple/app/phpunit.xml.dist!
    !
    PHP Fatal error: Call to a member function
    send() on null in /Users/saro0h/Documents/
    talks/symfonycon-madrid-2014/code-exemple/src/
    PoleDev/AppBundle/Security/
    GithubAuthenticator.php on line 43

    View full-size slide

  97. The null object expected is a:

    Guzzle\Http\Message\EntityEnclosingRequest $request
    !
    !
    Let’s provide it!

    View full-size slide

  98. $guzzleRequestObjectProphecy = $this
    ->prophet
    ->prophesize(‘Guzzle\Http\Message\EntityEnclosingRequest')
    ;
    !
    $guzzleRequest = $guzzleRequestObjectProphecy->reveal();

    View full-size slide

  99. ORIGINAL CODE (STEP 1: GET ACCESS TOKEN)
    $url = $this->router->generate(‘admin’,[], true);
    $endpoint = ‘/login/oauth/access_token’;
    !
    $request = $this->client->post($endpoint,[], [
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $url
    ]);
    !
    $response = $request->send();
    $data = $response->json();

    View full-size slide

  100. $clientObjectProphecy = $this->prophet!
    ->prophesize(‘Guzzle\Service\Client');!
    !
    $clientObjectProphecy!
    ->post('/login/oauth/access_token', [],
    [!
    'client_id' => ' ',!
    'client_secret' => ' ',!
    'code' => ' ',!
    'redirect_uri' => ' '!
    ])!
    ->willReturn($guzzleRequest)!
    ;!
    !
    $client = $clientObjectProphecy->reveal();

    View full-size slide

  101. ORIGINAL CODE (STEP 1: GET ACCESS TOKEN)
    $url = $this->router->generate(‘admin’,[], true);
    $endpoint = ‘/login/oauth/access_token’;
    !
    $request = $this->client->post($endpoint,[], [
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $url
    ]);
    !
    $response = $request->send();
    $data = $response->json();

    View full-size slide

  102. Create a stub for $request->send()

    This method must return a:

    Guzzle\Http\Message\Response $response
    !
    Let’s go for it!

    View full-size slide

  103. $guzzleResponseObjectProphecy = $this->prophet
    ->prophesize('Guzzle\Http\Message\Response');
    $guzzleResponse = $guzzleResponseObjectProphecy->reveal();
    !
    $guzzleRequestObjectProphecy = $this
    ->prophet
    ->prophesize(‘Guzzle\Http\Message\EntityEnclosingRequest')
    ;
    !
    $guzzleRequestObjectProphecy
    ->send()
    ->willReturn($guzzleResponse)
    ;
    !
    $guzzleRequest = $guzzleRequestObjectProphecy->reveal();

    View full-size slide

  104. Hurray! The original code is
    running with our dummies and
    stubs.

    But we do not test anything.

    View full-size slide

  105. WHAT WE NEED TO TEST
    AGAIN?

    View full-size slide

  106. public function createToken(Request $request, $providerKey)
    {
    $request = $this->client->post('/login/oauth/access_token', array(), array (
    'client_id' => $this->clientId,
    'client_secret' => $this->clientSecret,
    'code' => $request->get('code'),
    'redirect_uri' => $this->router->generate('admin', array(), UrlGeneratorInterface::ABSOLUTE_URL)
    ));
    !
    $response = $request->send();
    !
    $data = $response->json();
    !
    if (isset($data['error'])) {
    $message = sprintf('An error occured during authentication with Github. (%s)',
    $data['error_description']);
    $this->logger->notice(
    $message,
    array(
    'HTTP_CODE_STATUS' => Response::HTTP_UNAUTHORIZED,
    'error' => $data['error'],
    'error_description' => $data['error_description'],
    )
    );
    !
    throw new HttpException(Response::HTTP_UNAUTHORIZED, $message);
    }
    !
    return new PreAuthenticatedToken(
    ‘anon.',
    $data[‘access_token'],
    $providerKey
    );
    }
    We need to test
    the result of this
    method

    View full-size slide

  107. TEST THAT THE TOKEN IS WHAT WE NEED TO BE
    $token = $githubAuthenticator->createToken($request, ‘secure_area’);!
    !
    $this->assertSame('a_fake_access_token', $token->getCredentials());!
    $this->assertSame('secure_area', $token->getProviderKey());!
    $this->assertSame('anon.', $token->getUser());!
    $this->assertEmpty($token->getRoles());!
    $this->assertFalse($token->isAuthenticated());!
    $this->assertEmpty($token->getAttributes());!
    !

    View full-size slide

  108. Remember that output…

    !
    Github returns an access token at that point.

    View full-size slide

  109. $guzzleResponseObjectProphecy = $this->prophet-
    >prophesize('Guzzle\Http\Message\Response');
    !
    $guzzleResponseObjectProphecy
    ->json()
    ->willReturn([‘access_token' => ‘a_fake_access_token'])
    ;
    !
    $guzzleResponse = $guzzleResponseObjectProphecy->reveal();

    View full-size slide

  110. Hurray! The original code is running
    with our dummies and stubs.

    And it is tested !

    View full-size slide

  111. USING A MOCK THIS TIME
    !
    $guzzleResponseObjectProphecy
    ->json()
    ->willReturn(array(‘access_token' => 'a_fake_access_token'))
    ->shouldBeCalledTimes(1)
    ;
    Don’t expect to get a new assertion, as
    in PHPUnit

    View full-size slide

  112. public function tearDown()!
    {!
    $this->prophet->checkPredictions();!
    $this->prophet = null;!
    }
    Mandatory
    DON’T FORGET ABOUT THE CHECK

    View full-size slide

  113. WRONG EXPECTATION
    But if the expectation is not right, you’ll get an
    exception.
    !
    $guzzleResponseObjectProphecy
    ->json()
    ->willReturn(array(‘access_token' => 'a_fake_access_token'))
    ->shouldBeCalledTimes(10)
    ;

    View full-size slide

  114. TO SUM UP ALL OF THIS

    View full-size slide

  115. The Prophecy mock library
    philosophy is around the
    description of the future of an
    object double through a
    prophecy.
    Prophecy

    View full-size slide

  116. A prophecy must be revealed
    to get a dummy, a stub or a
    mock.
    Prophecy

    View full-size slide

  117. With PHPUnit, all is around the
    getMock() method.
    PHPUnit

    View full-size slide

  118. The first step is to get a mock,
    then describe the future of the
    double of the object.
    PHPUnit
    PHPUnit

    View full-size slide

  119. $dummy = $this->getMock(‘Foo\Bar’);
    !
    ———————————————————————————————————————
    !
    $prophet = new \Prophecy\Prophet;
    $prophecy = $prophet->prophesize(‘Foo\Bar’);
    $dummy = $prophecy->reveal();
    PHPUnit
    Prophecy

    View full-size slide

  120. $prophecy
    ->send()
    ->willReturn($valueToReturn)
    ;
    ——————————————————————————————————————————
    $dummy
    ->method('send')
    ->willReturn($valueToReturn)
    ;
    Prophecy
    PHPUnit

    View full-size slide

  121. Extensible.

    !
    ———————————————————————————————————————
    !
    Not extensible.
    Prophecy
    PHPUnit

    View full-size slide

  122. Resources

    • https://github.com/phpspec/prophecy

    • https://phpunit.de/manual/4.5/en/test-
    doubles.html#test-doubles.prophecy

    • all the code is here: http://bit.ly/11pnp2I

    View full-size slide

  123. Thank you!
    @saro0h
    joind.in/talk/view/12957
    sarah-khalil.com/talks
    saro0h

    View full-size slide