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