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

PHP Testing and Mocking

PHP Testing and Mocking

Farzad Ghanei

April 19, 2017
Tweet

More Decks by Farzad Ghanei

Other Decks in Programming

Transcript

  1. On Testing Tests Help to • keep the code base

    under control • have more modular and well structured code • new team members to be productive sooner • team members to stay productive
  2. • Test expected behaviors, focus on “what” than “how” •

    Treat tests as live documentation • Let the test describe the expected behavior • Fail the test first, then pass them On Writing Tests
  3. On Mocking • Mocking helps to handle dependencies • Mocking

    helps tests be focused • Mocking can help tests to run faster by abstracting external resources
  4. Some Testing Techniques • Use data providers • Setting expected

    exception before the call to tests • Anonymous function for complex param assertion (returnCallback()) ◦ with(‘p1’, ‘p2’) / withConsecutive([[‘p1’, ‘p2’], [‘p21’, ‘p22’]]) • Anonymous functions for complex expected returns (returnCallback()) ◦ $this->willReturn(‘foo’) / $this->will($this->return(‘foo’)) ◦ $this->will(returnArgument(0) / onConsecutiveCalls([‘r1’, ‘r2’]) / returnValueMap([‘p1’, ‘p2’, ‘r’]))
  5. PHPUnit Mocking • Mock existing classes • Partial mocking •

    Expectations ◦ Call count ◦ Params • ...
  6. Mockery • Mock any class/function • Partial mocking • Expectations

    ◦ Call count ◦ Params • Integration with PHPUnit (test runner) • ...
  7. Some Mockery Quirks • Integration with PHPUnit (test runner) •

    No call count, means no call is OK • Mocking not existing classes (prefer partial) • Mocking method calls in order ◦ Mocking method multiple times won’t work ◦ Can use callback function • Some equality assertions need explicit Hamcrest checks (like HHVM collections)
  8. • Make tests fail, then pass them • Use mocking

    when helps • Benefit from data providers • Exception assertion closest to expected place • Be aware of the quirks Summary