0

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

Benjamin B.
  • 473
  • 5
  • 15

1 Answers1

3

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.

Stefano Sala
  • 907
  • 4
  • 7
  • Sound advice about injecting required services. However he could also mock the container if needed and return a session service mock when the get method is called passing "session": http://stackoverflow.com/questions/277914/how-can-i-get-phpunit-mockobjects-to-return-differernt-values-based-on-a-paramet/292423#292423 – Luke Oct 10 '13 at 05:28