Slide 1

Slide 1 text

Mockery ● @robertbasic ● https://github.com/robertbasic/ ● http://robertbasic.com/

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

What to use? ● A mocking framework ● PHPUnit's built-in mock stuff ● FBMock ● Phake ● ...

Slide 5

Slide 5 text

Mockery!

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

Installing ● composer require mockery/mockery ● https://github.com/padraic/mockery

Slide 8

Slide 8 text

Connect with PHPUnit ● Add the listener in phpunit.xml

Slide 9

Slide 9 text

Bootstrap ● Set up autoloading and stuff

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

A simple example

Slide 12

Slide 12 text

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.

Slide 13

Slide 13 text

Expectations for method calls

Slide 14

Slide 14 text

Argument validation ● with($param1, $param2); ● withAnyArgs(); ● withNoArgs(); ● with(m::type('\Foo\Bar')); ● with(m::on(closure)); ● with($regex);

Slide 15

Slide 15 text

Return values ● andReturn($value); ● andReturn($firstRun, $secondRun, $thirdRun); ● andReturnUsing(function($x) { return $x * 2 }); ● andThrow(Exception);

Slide 16

Slide 16 text

But you can also read all that in the documentation

Slide 17

Slide 17 text

Some REAL examples

Slide 18

Slide 18 text

Don't touch the database!

Slide 19

Slide 19 text

Don't call that service!

Slide 20

Slide 20 text

Don't call that code!

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

Closure to validate arguments

Slide 23

Slide 23 text

Regex to validate arguments

Slide 24

Slide 24 text

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.

Slide 25

Slide 25 text

Thanks! ● Questions? ● @robertbasic ● https://github.com/padraic/mockery