Although not everyone is doing it yet, testing your application is one of the most essential parts of being a developer. Unit tests are the most common tests to run. With unit tests, you can check if a class behaves exactly like you intended it too. Sometimes, you are using a third party service within your application and it’s hard to get everything set up to get this unit tested. That’s exactly when mocking comes into play.
What is mocking?
Mocking an object is nothing more than creating a stand-in object, which replaces the real object in a unit test. If your application heavily relies on dependency injection, mocking is the way to go.
There can be several reasons to mock objects
- When performing unit tests, it’s best to isolate the class. You don’t want another class or service to interfere with your unit test.
- The object doesn’t exist yet. You can first create the tests, then build the final objects.
- A mock object is in generally faster than preparing a whole database for your test.
When running unit tests, you are probably using PHPUnit. PHPUnit comes with some default mocking abilities as you can see in the documentation. You can read more about mocking in general and the mocking abilities from PHPUnit in this article written by Jeune Asuncion.
In this article, we will dive into Mockery, a library created by Pádraic Brady. We will create a temperature class which gets a currently non existing weather service injected.
Setup
Let’s start by setting up our project. We start off with a composer.json
file which contains the following content. This will make sure we have mockery and PHPUnit available.
{
"name": "sitepoint/weather",
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.3.3"
},
"autoload": {
"psr-0": { "": "src/" }
},
"require-dev": {
"phpunit/phpunit": "4.1.*",
"mockery/mockery": "0.9.*"
}
}
We also create a PHPUnit config file named phpunit.xml
<phpunit>
<testsuite name="SitePoint Weather">
<directory>src</directory>
</testsuite>
<listeners>
<listener class="\Mockery\Adapter\Phpu
Truncated by Planet PHP, read more at the original (another 879 bytes)
more
{ 0 comments... » Mock your Test Dependencies with Mockery read them below or add one }
Post a Comment