Here are the steps I used to successfully get PHPUnit working in MAMP. These instructions
are pieced together from various places. I hope that having it all in one place helps
someone else. Happy testing!
Use MAMP's PHP in the Terminal
Adapted from How to override the path of PHP to use the MAMP path?
Edit or create ~/.bash_profile
with the lines below
# Use MAMP's latest version of PHP
MAMP_LATEST_PHP=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`
export PATH=/Applications/MAMP/bin/php/${MAMP_LATEST_PHP}/bin:$PATH
Place these lines after any other lines exporting $PATH - this assures that your MAMP PHP is found first in the path. Note that these lines try to find the highest numbered version of PHP in your MAMP installation. Feel free to adjust this to a specific one that you have, if desired.
You can tell you did it right when you get a MAMP path from which php
in your terminal. You should get something like this:
/Applications/MAMP/bin/php/php7.0.0/bin/php
Install PHPUnit
Mostly, this is downloading the PHP archive (PHAR) from the PHPUnit website. There are ways to do this from the command line that I couldn't get to work. So, I used a web browser.
- Download the most recent PHPUnit PHAR from https://phar.phpunit.de
- Move it to
/usr/local/bin
cd /usr/local/bin
- Make it executable with
chmod +x phpunit-5.3.2.phar
(adjust according to actual name)
- Make a symbolic link with
ln -s phpunit-5.3.2.phar ./phpunit
(adjust according to actual name)
- Check the version with
phpunit -—version
You should get something like this:
PHPUnit 5.3.2 by Sebastian Bergmann and contributors.
Building a symbolic link in step 5 permits you to use phpunit
instead of having to type
phpunit-5.3.2.phar
instead. It also allows you to update PHPUnit without having to
change what you type, assuming of course that you create a new symbolic link when you
update.
Write a Test
This isn't an exhaustive section. There are far better tutorials on writing tests.
Instead, this is merely some notes from my experience on rules that tripped me up,
though I'm sure everyone else knows them:
- Your test class name must end with Test:
class SomeTest extends PHPUnit_Framework_TestCase
- Your test class file name must end with Test.php and match the contained class:
SomeTest.php
- Method names in your test class that are to be run as tests must start with test:
public function testSomething()
Run a Test
By this time, it should be as easy as:
phpunit SomeTest
If everything goes well, PHPUnit will run your test and give you the results.
Add a Handy Alias
Assuming that it all works (Yay!) try this alias in your ~/.bash_profile
# Use colors when running phpunit
alias phpunit='phpunit --colors'