Introduction
This article is about creating a simple phpunit test in Symfony. The reason you would want to run phpunit tests, is to verify that code changes you made still work. For example, if you query a home page, you are going to “expect” certain things to be on that page and when you make development code changes, when you run your phpunit test, you should get the same results. In other words, the tests should pass (unless you are expecting failures).
Symfony Documentation
Symfony has fairly good documentation on how to get started writing phpunit tests on their Testing page. This is a good place to start reading to get familiar with the Goutte crawler and some basic testing.
A Simple Test
The following is some sample code that I used to run a simple phpunit test:
<?php
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase{
public function testIndex(){
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$this->assertContains(
'Application System',
$client->getResponse()->getContent()
);
$this->assertCount(1, $crawler->filter('h1'));
$this->assertGreaterThan(
2,
$crawler->filter('a')->count()
);
}
}
The above code simply gets the path “/”, which is the main page, then asserts the following:
- HTML response code is “
200
”. - The page contains the text “
Application System
”. - There is an exact count of 1 “
h1
” HTML tag. - There are greater than 2 “
a
” HTML link tags.
For item 4, I am expecting that to fail, because I know that in my case I have exactly 2 “a
” link tags on the page.
Running the Tests
To run the phpunit tests, from the Symfony project root folder, run the following command:
phpunit
The tests will run and you should see a response similar to the following:
Notice the failure at step 4 as I expected. The PHPUnit version is also shown on the first output line.
This gives you an idea how to run a simple phpunit tests in Symfony. Hopefully this helps you out.