简体   繁体   English

使用其他服务的Symfony2单元测试服务类

[英]Symfony2 unit testing service class using other services

I'm doing some unit testing (phpunit) for a Symfony2 Bundle and i want to test this method : 我正在为Symfony2 Bundle做一些单元测试(phpunit),我想测试这个方法:

/**
 * 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 ? 在我的测试中,似乎我需要Symfony2服务容器才能使用会话,但是如何在没有Symfony2 AppKernel.php依赖项的情况下对该单元进行单元测试?

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 . 例如,在这种情况下,您应该只注入session

Doing this lets you mock the session object and check if, for example, the method getFlashBag is getting called. 这样做可以模拟会话对象,并检查例如是否调用了getFlashBag方法。

If you need the container in your class, I suggest you to functionally test it with WebTestCase . 如果您在课堂上需要该容器,建议您使用WebTestCase进行功能测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM