How to speed up your PHPunit tests in Laravel 5?
Testing is good. I’m a big fan of well tested code but nobody likes waiting tests to be finished. It is ok when you have a few hundreds of them or less. But when we reached a 2K number it became a really frustrating issue.
In our case all integration and unit test lasted nearly for 1 hour:
2000 tests => 60 minutes
So we tried to optimize test execution efficiency.
First we reviewed our model factories and fixed one small issue:
//old
array_get($overrides, 'user_id', factory(User::class)->create()->id)//new
array_get($overrides, 'user_id') ?? factory(User::class)->create()->id
The problem is that 3rd parameter in array_get function is always executed and takes some time.
We saved nearly 10 minutes after changing that small piece of code.
Then we cleared out our database seeders. It saved us nearly 5 minutes more.
Next step was fixing issue with files. We replaced Amazon S3 with minio server. Now all files are stored locally but using same API as Amazon S3. It saved us another 10 minutes.
Then we mocked up as many third party services as possible. It needs some effort but it worth it. Another 5 minutes were saved.
Finally we added native caching:
php artisan config:cache
php artisan route:cache
It saved us another 5–10 minutes. If you have a lot of API calls and big config file you have to use that in your test script.
Summary:
2000 tests => 15-20 minutes
So we optimize speed more then 3x time.
Hope you will use my advices in your project to speed up your tests and save your neurons:)
And please share your tips about Phpunit optimization:)