duanniu3385 2013-10-09 18:46
浏览 63
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dongpao1918 2013-10-09 20:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集