Save 37% off PRO during our Black Friday Sale! »

Mockery

 Mockery

A short talk about Mockery, how to start using it, what are it's different parts, some gotchas and real-life examples that are bit more complicated than what fits into the official documentation.

Presented at the phpnl15 uncon.

6d9ae403ee630c0e51ec79105a3b7af1?s=128

robertbasic

January 24, 2015
Tweet

Transcript

  1. Mockery • @robertbasic • https://github.com/robertbasic/ • http://robertbasic.com/

  2. Problems with unit testing • Code that uses 3rd party

    services and APIs • Databases • Parts of our code that are not relevant to the code we are testing
  3. How do we fix it? • Avoid calls to the

    database • Avoid calls to 3rd party services and APIs • Avoid calls to parts of our own code • Mock out the moving bits
  4. What to use? • A mocking framework • PHPUnit's built-in

    mock stuff • FBMock • Phake • ...
  5. Mockery!

  6. What's Mockery? • A framework to mock objects • Easy

    to use with PHPUnit (and maybe other unit testing tools?) • Makes mocking a lot saner than the built-in PHPUnit stuff • Developed by @padraicb and lots of help from @davedevelopment
  7. Installing • composer require mockery/mockery • https://github.com/padraic/mockery

  8. Connect with PHPUnit • Add the listener in phpunit.xml

  9. Bootstrap • Set up autoloading and stuff

  10. A simple example • Foo has a dependency on Bar

    • Foo calls a method on Bar that returns something • We don't want to call the real Bar's method, but a mock • This gets more complicated in real life
  11. A simple example

  12. Expectations for method calls • shouldReceive('methodName'); • once(), twice(), zeroOrMoreTimes(),

    times(n), never() • If no expectation is set on the number of calls, it will surprise you.
  13. Expectations for method calls

  14. Argument validation • with($param1, $param2); • withAnyArgs(); • withNoArgs(); •

    with(m::type('\Foo\Bar')); • with(m::on(closure)); • with($regex);
  15. Return values • andReturn($value); • andReturn($firstRun, $secondRun, $thirdRun); • andReturnUsing(function($x)

    { return $x * 2 }); • andThrow(Exception);
  16. But you can also read all that in the documentation

  17. Some REAL examples

  18. Don't touch the database!

  19. Don't call that service!

  20. Don't call that code!

  21. Mocking hard dependencies • You know all those “new” statements

    in your legacy code? • http://robertbasic.com/blog/mocking-hard- dependencies-with-mockery • https://github.com/robertbasic/mockery- hard-dependency
  22. Closure to validate arguments

  23. Regex to validate arguments

  24. Crazy bits • Doesn't do a diff on method arguments

    that are arrays • Reflection can go nuts with PHP classes • __magic methods... yea, don't.
  25. Thanks! • Questions? • @robertbasic • https://github.com/padraic/mockery