Get up and running with PHPUnit testing easily for your project with this skeleton
- Are you frustrated with trying to install and configure PHPUnit?
- Are you wishing you could use just one command and BANG it was all done for you and you could get on with writing your beautiful unit tests?
- Are you having sleepless nights or sleepy afternoons?
Well, I'm happy to let you know that you just need to clone this repo and all your problems will be whisked away (apart from the last one, perhaps).
We have also included a sample PHP class so you can learn a few tricks in how to use PHPUnit in your projects!
- PHP 8.2 or higher
- Composer
- Open a Terminal. Download the repo with
git clone https://github.com/jasdeepkhalsa/phpunit-skeleton.git cdinto where you downloaded your repo and runcomposer install
- Open a Terminal
cdto your project root- Run
composer test(or./vendor/bin/phpunitdirectly) and...magic! Tests (should) now be running!
You should see something like...
PHPUnit 11.x by Sebastian Bergmann and contributors.
Runtime: PHP 8.3.x
Configuration: /(directory)/phpunit-skeleton/phpunit.xml
.. 2 / 2 (100%)
Time: 00:00.010, Memory: 8.00 MB
OK (2 tests, 3 assertions)
This skeleton ships with PHP-CS-Fixer configured for the PSR-12 coding standard.
- Check for violations:
composer cs-check - Automatically fix violations:
composer cs-fix
Once you've successfully installed PHPUnit Skeleton, you'll probably want to customize it to your application.
Once you have the name of your application which we shall refer to as YourApp, then do the following:
-
First you have to change the entry
Applicationin thecomposer.jsonfile toYourAppunderautoload.psr-4(andautoload-dev.psr-4if you keep the same pattern for tests):{ "autoload": { "psr-4": { "YourApp\\": "lib/" } }, "autoload-dev": { "psr-4": { "Tests\\": "tests/" } } } -
Update the
namespaceinside the following PHP files:- Inside
/lib/Example.phpupdatenamespace Application;tonamespace YourApp; - Inside
/tests/ExampleTest.phpupdateuse Application\Example;touse YourApp\Example;
- Inside
-
Run
composer dump-autoloadto refresh the autoloader -
Run
composer testagain to make sure all tests are passing again
- To the wonderful people on Stack Overflow for helping me understand PHPUnit better
- Constant support from PHP Guru Jujhar Singh from Buto who also inspired the test case style used in the examples
- Class examples inspired from video by Jeffrey Way from Nettuts+
- Email: jasdeep {at} simplyspiritdesign {dot} com
- Twitter: @JasdeepKhalsa1