I'm doing some unit testing (phpunit) for a Symfony2 Bundle and i want to test this method :
/**
* Set a flash notification
* @param array $message
*/
public function setFlashNotification(array $message) {
if (!isset($message['key'])) {
throw new \ErrorException("Message array must contains a key");
}
if (!isset($message['content'])) {
throw new \ErrorException("Message array must contains a content");
}
$this->container->get('session')->getFlashBag()->add(self::SESSION_KEY . $message['key'], $message['content']);
}
In my tests it seems i need Symfony2 service container to use the session, but how can i unit test this method without Symfony2 AppKernel.php dependency ?
Thanks
I assume that this method is part of a class. As a best practice, this class should not receive the whole container as a dependency, but should require only a subset of strictly required dependencies. For example, in this case, you should inject only session
.
Doing this lets you mock the session object and check if, for example, the method getFlashBag
is getting called.
If you need the container in your class, I suggest you to functionally test it with WebTestCase
.