TLDR; Don't use the base TestCase which ships with laravel out of the box. If your tests don't require Laravel specific functionality, Using PHPUnit's base TestCase is more than 4 times faster.
Benchmark
For this test, I'm using the latest version of Laravel (7.25.0) on a Macbook Pro with 16GB RAM and a 2.3 GHz Quad-Core Intel Core i5 processor.
Setup
- Install Laravel from the official guide here
-
Create a class called
Math
inapp/Math.php
<?php declare(strict_types=1); namespace App; class Math { function sum(int $first, int $second): int { return $first + $second; } }
-
Add the test file
MathTest.php
intests/Unit
<?php declare(strict_types=1); namespace Tests\Unit; use App\Math; use Tests\TestCase; class MathTest extends TestCase { /** * @dataProvider provideDataForSum * * @param int $first * @param int $second * @param int $expectedResult */ function testSum(int $first, int $second, int $expectedResult) { $math = new Math(); $actualResult = $math->sum($first, $second); $this->assertEquals($expectedResult, $actualResult); } public function provideDataForSum(): array { return [ 'sum two zeros (0 + 0 = 0)' => [ 0, 0, 0 ], 'sum negative and positive number (-1 + 3 = 2)' => [ -1, 3, 2 ], 'sum two positive numbers (1 + 6 = 7)' => [ 1, 6, 7 ], 'sum two negative numbers (-4 + -8 = -12)' => [ -4, -8, -12 ] ]; } }
-
Run the tests using
./vendor/bin/phpunit tests/Unit/MathTest.php
Results: Time: 138 ms, Memory: 16.00 MB
Change line 8 in
MathTest.php
withuse PHPUnit\Framework\TestCase;
-
Run the tests again using
./vendor/bin/phpunit tests/Unit/MathTest.php
Results: Time: 33 ms, Memory: 6.00 MB
Conclusion
The test with laravel's base test case is 418%
slower than the tests with PHPUnit's base test case. Also, This is just 1 test, Imagine how much time you will save on a project with more than 1000 test.
NOTE: From laravel 6.0, The ExampleTest.php
file in tests/Unit
now uses PHPUnit\Framework\TestCase;
but If you are coming from an old version of laravel you may be using the laravel base test Tests\TestCase;
instead.
Top comments (0)