Tuesday, September 29, 2015

BasicBlogBundle - Functional Testing with PHPUnit

Reading about testing controllers in Symfony I found this post on stackoverflow which brings arguments that controller shouldn't be unit tested:  http://stackoverflow.com/questions/10126826/how-can-i-unit-test-a-symfony2-controller

It makes sense, I will than write functional tests for my controllers.Working with PHPUnit and Symfony (how I did):

1. Install PHPUnit

Install PHPUnit globally on your machine following the instructions found here:
https://phpunit.de/manual/current/en/installation.html

2. Configuration
In "app" directory  there is the file phpunit.xml.dist
Make a copy of it and rename it to phpunit.xml
Do any changes you consider necessary inside of it (I didn't changed anything).
Under "\src\CPANA\BasicBlogBundle\Tests\Controller" Symfony adds an example test class: DefaultControllerTest.php. I've edited that file to test by BlogController class:
"BlogControllerTest.php"

3. Write your test class
The test will verify if the the requested page contains the word "blog" which is in the title of the page expected.

class BlogControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();
        $client->request('GET', '/blog');
        //var_dump($client->getResponse()->getContent());
       
        $crawler = $client->request('GET', '/blog');
        $this->assertGreaterThan(
            0,
            $crawler->filter('html:contains("Blog")')->count()
        );
    }
}


4.Run PHPUnit
Open command prompt, navigate to the folder where Symfony is installed. Run command:
    phpunit -c app "src/CPANA/BasicBlogBundle/"> "phpunitLog.txt"

this command will log the output in a text file. Review the log file found in the root path of Symfony.
If you are lucky the output will look like this:

PHPUnit 4.8.8 by Sebastian Bergmann and contributors.

.Time: 4.89 seconds, Memory: 24.75Mb

OK (1 test, 1 assertion)


Next challenge should be to test aspects that depend on the interaction with the database:
http://symfony.com/doc/current/cookbook/testing/database.html

No comments:

Post a Comment