- Unit Testing Tutorial Part I: Introduction to PHPUnit
- Unit Testing Tutorial Part II: Assertions, Writing a Useful Test and @dataProvider
- Unit Testing Tutorial Part III: Testing Protected/Private Methods, Coverage Reports and CRAP
- Unit Testing Tutorial Part IV: Mock Objects, Stub Methods and Dependency Injection
- Unit Testing Tutorial Part V: Mock Methods and Overriding Constructors
Previously in my PHPUnit tutorial series, you learned about the very powerful concept of mock objects and stub methods. This concept is central to successful unit testing, and once it fully ‘clicks’ in your head you will start to realize how useful and simple testing can be.
There is also another thing I want to make clear: creating tests is basically a puzzle - you simply have to go step by step, making sure all the pieces fit together correctly so you can get your green. I hope to make clear what I mean by the end of this tutorial.
INTRODUCING MOCK METHODS
In my previous tutorial you learned all about mock objects and stub methods. There is another very similar concept you must also know about: mock methods.
A mock object is an object that you would create using PHPUnit’s
getMockBuilder() method. It is basically an
object that extends the class you define and allows you to perform nifty tricks and assertions on it.
A stub method is a method contained within a mock object that returns
null by default, but allows you to
easily override the return value.
A mock method is pretty simple - it does the exact same thing its original method would. In other words any
code that is in the method you are mocking will actually run and will not return
null by default
(unless that is what it originally did).
Mark Nichols gives a very good explanation of what the difference between mock and stub methods are.
Basically mock methods are useful for when you want the code inside of it to run, but also want to do some assertions on the behavior of the method. These assertions could be that specific parameters are passed to the method (if it applies), or that the method is called exactly 3 times or not at all.
Do not worry if this does not make immediate sense yet.