【问题标题】:Writing tests for a Symfony2 service that uses the database为使用数据库的 Symfony2 服务编写测试
【发布时间】:2014-07-06 18:44:10
【问题描述】:

我正在为 Symfony2 创建一个小包,它只是提供服务;可以调用它在数据库中插入一行,包含几个参数:

class AuditLogService {

 private $em;

 public function __construct(EntityManager $em)
 {
  $this->em = $em;
 }  

 public function log($type, $channel, $message) {
  $log = new AuditLog();
  $log->setType($type);
  $log->setChannel($channel);
  $log->setMessage($message);
  $this->em->persist($log);
  $this->em->flush();
 }
}

现在我需要为它编写一个测试,所以基本上这里是我假设我应该采取的步骤:

  1. 编写一个获取记录器服务的测试,但改用模拟 entityManager

  2. 在使用模拟 em 的记录器上调用函数

  3. 尝试使用我在步骤 2 中使用的参数从模拟的 em 中取回它

  4. 判断我是否找到结果

我很确定理论上这些是正确的步骤,但是任何人都可以为我指出正确的方向吗?

我有这个:

public function testServiceLoaded()
    {
       $this->assertEquals(get_class($this->container->get('bbit_audit_log.service')), 'BBIT\AuditLogBundle\Services\AuditLogService');
    }

这会返回以下错误:

“bbit_audit_log.service”依赖于不存在的服务“doctrine.orm.entity_manager”

我的容器似乎不包含entitymanager

【问题讨论】:

    标签: symfony


    【解决方案1】:

    在单元测试中跳过 3 和 4。AuditLogService 不负责保存在数据库中(而是调用 em)。 3和4应该通过功能测试来测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-29
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多