Dieses Blog durchsuchen

Sonntag, 17. Juli 2016

symfony 3: create a unittest for an api controller

In one of my last post
http://magento2-tuts.blogspot.de/2016/07/symfony3-create-restful-api-controller.html , we have created a restful api controller.

Now we want to write a unittest to test this controller.


install phpunit:
apt-get install phpunit

configure phpunit.xml
-in your projectroot there is a file phpunit.xml.dist Rename it to phpunit.xml
- open the file and add your BundleDirectory to the directory object
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="app/autoload.php"
>
<php>
<ini name="error_reporting" value="-1" />
<server name="KERNEL_DIR" value="app/" />
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
<directory>src/Check/BlogBundle/Tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>src</directory>
<exclude>
<directory>src/*Bundle/Resources</directory>
<directory>src/*/*Bundle/Resources</directory>
<directory>src/*/Bundle/*Bundle/Resources</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
view raw phpunit.xml hosted with ❤ by GitHub

In my case i had to add the src/Check/BlogBundle/Test/ directory

Now we can add a controllerTest.

Lets say, we want to test, that the service throws 500 if we try to POST an empty user to the database:
<?php
namespace Check\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class UserApiTest extends WebTestCase
{
public function testRouteIsAvaliable()
{
$client = static::createClient();
$crawler = $client->request('POST' ,'/api/user');
$this->assertEquals(500, $client->getResponse()->getStatusCode());
}
}
view raw UserApiTest hosted with ❤ by GitHub
 

Run your test:
open your terminal in your projectroot and type: phpunit -c phpunit.xml

Thats all your testresults are found in the console.

Keine Kommentare:

Kommentar veröffentlichen