Create a PHPUnit Test
Learn how to create a PHPUnit test in the Symfony web application.
We'll cover the following
Now that we have created a page and a PHP function, we can make some tests to run on our web application. This follows proper CI/CD processes, as we should always run tests on our code before deploying to web servers.
Set up PHPUnit
First, we’ll need to add the PHPUnit Composer package to run tests.
- In the terminal below, run:
composer require --dev symfony/test-pack
This will install development testing environment packages for running tests in our Symfony web application.
Now, run unit tests by running this command:
php bin/phpunit
We should get No tests executed!
. This is because we don’t have tests yet. We’ll add a test in the next step.
We can now move on to create a PHPUnit test.
Write a PHPUnit test
Now, we are ready to create a unit test.
- Under the
tests/Controller
folder in the SPA widget below, there is aNewPageControllerTest.php
file created for you. - Add the code below to this
NewPageControllerTest.php
file.- This code is a new PHPUnit class with a
testSomething
function, which creates aNewPageContoller
class that we created before. It calls thepersonalMessage
function and finally makes sure it returnsPHP is cool
.
- This code is a new PHPUnit class with a
<?phpnamespace App\Tests;use PHPUnit\Framework\TestCase;use App\Controller\NewPageController;class NewPageControllerTest extends TestCase{public function testSomething(){$newPage = new NewPageController;$this->assertEquals("PHP is cool", $newPage->personalMessage());}}
- Now, click the “Run” button in the SPA widget.
- After the app loads, run the test in the terminal.
- Click the plus icon to open a new terminal tab.
- Run
cd /usercode
. - Then, run the following command to run the PHPUnit test:
php bin/phpunit
The terminal output should show the following. This indicates our test ran, and it passed!
educative@educative:~/symfony-app/usercode$ php bin/phpunit
PHPUnit 9.5.26 by Sebastian Bergmann and contributors.
Testing
. 1 / 1 (100%)
Time: 00:00.018, Memory: 10.00 MB
OK (1 test, 1 assertion)
#!/usr/bin/env php <?php use App\Kernel; use Symfony\Bundle\FrameworkBundle\Console\Application; if (!is_file(dirname(__DIR__).'/vendor/autoload_runtime.php')) { throw new LogicException('Symfony Runtime is missing. Try running "composer require symfony/runtime".'); } require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; return function (array $context) { $kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); return new Application($kernel); };
Summary
In this lesson, we set up our project to run PHPUnit tests and created a PHPUnit test, which tests our NewPageController
personalMessage
PHP function.
Well done on creating the PHPUnit test!