DEV Community

αςнο αяηοℓδ
αςнο αяηοℓδ

Posted on • Originally published at acho.arnold.cf

One Trick to speed up your unit tests with Laravel

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

  1. Install Laravel from the official guide here
  2. Create a class called Math in app/Math.php

    <?php
    
    declare(strict_types=1);
    
    namespace App;
    
    class Math
    {
        function sum(int $first, int $second): int {
            return $first + $second;
        }
    }
    
  3. Add the test file MathTest.php in tests/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
                ]
            ];
        }
    }
    
  4. Run the tests using

    ./vendor/bin/phpunit tests/Unit/MathTest.php
    
  5. Results: Time: 138 ms, Memory: 16.00 MB

  6. Change line 8 in MathTest.php with use PHPUnit\Framework\TestCase;

  7. Run the tests again using

    ./vendor/bin/phpunit tests/Unit/MathTest.php
    
  8. 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.

Discussion (0)