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

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.

robertbasic

January 24, 2015
Tweet

More Decks by robertbasic

Other Decks in Programming

Transcript

  1. 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
  2. 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
  3. What to use? • A mocking framework • PHPUnit's built-in

    mock stuff • FBMock • Phake • ...
  4. 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
  5. 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
  6. 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.
  7. Argument validation • with($param1, $param2); • withAnyArgs(); • withNoArgs(); •

    with(m::type('\Foo\Bar')); • with(m::on(closure)); • with($regex);
  8. 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
  9. 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.