We now have several class files that are not related to the controllers, meaning we can run unit tests against them. Still, we won't be going after a full code coverage as part of this book, rather focus on some of the little-big things, like using containers within our test classes.
We start of by adding the following line under the testsuites element of our phpunit.xml.dist file:
<directory>src/Foggyline/CatalogBundle/Tests</directory>
With that in place, running the phpunit command from the root of our shop should pick up any test we have defined under the src/Foggyline/CatalogBundle/Tests/ directory.
Now let's go ahead and create a test for our Category service menu. We do so by creating an src/Foggyline/CatalogBundle/Tests/Service/Menu/CategoryTest.php file with the following content:
namespace Foggyline\CatalogBundle\Tests\Service\Menu;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Foggyline\CatalogBundle\Service\Menu\Category;
class CategoryTest extends KernelTestCase
{
private $container;
private $em;
private $router;
public function setUp()
{
static::bootKernel();
$this->container = static::$kernel->getContainer();
$this->em = $this->container->get('doctrine.orm.entity_manager');
$this->router = $this->container->get('router');
}
public function testGetItems()
{
$service = new Category($this->em, $this->router);
$this->assertNotEmpty($service->getItems());
}
protected function tearDown()
{
$this->em->close();
unset($this->em, $this->router);
}
}The preceding example shows the usage of the setUp and tearDown method calls, which are analogous in behavior to the PHP's __construct and __destruct methods. We use the setUp method to set the entity manager and router service that we can use through out the rest of the class. The tearDown method is merely a clean up. Now if we run the phpunit command, we should see our test being picked up and executed alongside other tests.
We can even target this class specifically by executing a phpunit command with the full class path, as shown here:
phpunit src/Foggyline/CatalogBundle/Tests/Service/Menu/CategoryTest.php
Similarly to what we did for CategoryTest, we can go ahead and create OnSaleTest; the only difference between the two being the class name.