Skip to content

Symfony 7: Unit Tests

  • PHPUnit: Unit Testing with a Bite!
  • test a specific part of the system (class, or method);
  • do not use real data / external services; if class/method requires external stuff, use mocks;

Use a newer version of PHPUnit

  • Symfony uses by default v9;
  • Use steps below to use a newer version, while still using the Symfony recommended software from the tutorials.

Install PHPUnit specifically, using the wanted version

{
  "require-dev": {
    "phpunit/phpunit": "^10"
  },
  "scripts": {
    "test" : "XDEBUG_MODE=coverage vendor/bin/phpunit --colors=always --configuration vendor/webservco/coding-standards/phpunit/phpunit-10.xml --display-deprecations --display-errors --display-incomplete --display-notices --display-skipped --display-warnings",
    "test:dox" : "@test --testdox"    
  }
}

Run tests, make sure phpunit v10 is used.

  • use the custom command, to make sure the vendor/bin/phpunit is used;

Install symfony/test-pack

composer require --dev symfony/test-pack
 symfony/phpunit-bridge  instructions:

  * Write test cases in the tests/ folder
  * Use MakerBundle's make:test command as a shortcut!
  * Run the tests with php bin/phpunit

Notes

  • If using the recommended command bin/phpunit, v9 will be used;
  • If setting a newer phpunit version in phpunit.xml.dist, "SYMFONY_PHPUNIT_VERSION", that version will be installed/used, however the command will fail with the error:
PHP Fatal error:  Uncaught Error: Class "PHPUnit\TextUI\Command" not found in /home/radu/p/fastricambi/clippartsws-demo/vendor/symfony/phpunit-bridge/Legacy/CommandForV9.php:25
  • Issue, opened since 2023: https://github.com/symfony/symfony/issues/49069

Data provider

class Test
{
    #[DataProvider('someProvider')] 
    public function test($foo, $bar): void
    {
        ...
    }

    public static function someProvider(): \Generator
    {
        yield 'Name of current parameters' => ['fooValue1', 'barValue1'];
        yield 'Name of current parameters' => ['fooValue2', 'barValue2'];
    }
}

Mocking

  • mock: assert how the object is being used (expects, method, with, willReturn, etc);
  • stub: control the return value of the methods;

Mocking: Test Doubles

  • fake objects, return empty data;

Mocking: Stubs

  • fake objects where we optionally take control of the values they return;

Mocking: Mock Objects

  • also test data passed into the mock