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. PHP Testing and Mocking
    Some techniques and quirks.
    Farzad Ghanei

    View Slide

  2. 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

    View Slide

  3. On Testing
    Writing tests is a necessity

    View Slide

  4. ● 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

    View Slide

  5. On Mocking
    ● Mocking helps to handle dependencies
    ● Mocking helps tests be focused
    ● Mocking can help tests to run faster by abstracting external resources

    View Slide

  6. On Mocking
    ● Mocking is a good technique
    ● Beware of too much mocking

    View Slide

  7. 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’]))

    View Slide

  8. PHPUnit Mocking
    ● Mock existing classes
    ● Partial mocking
    ● Expectations
    ○ Call count
    ○ Params
    ● ...

    View Slide

  9. Some PHPUnit Mocks Quirks
    ● PHPUnit mocks and Hack
    ● PHPUnit mocks in data providers

    View Slide

  10. Let’s see some code

    View Slide

  11. Mockery
    ● Mock any class/function
    ● Partial mocking
    ● Expectations
    ○ Call count
    ○ Params
    ● Integration with PHPUnit (test
    runner)
    ● ...

    View Slide

  12. 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)

    View Slide

  13. More code ...

    View Slide

  14. ● 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

    View Slide