dstm2014 2013-12-11 22:41
浏览 43
已采纳

如何单元测试创​​建Zend \ Db \ Sql \ Sql对象的方法?

I have this method that I would like to unit test. Since it's creating the Sql object inside the method, I can't mock it.

Initially I thought about making Sql be an instance property except that I'd have to reset it every time I use it in other methods and this will most likely lead to hard to debug errors (I don't want the possibility to get a "dirty" Sql object on other subsequent calls to its getter if at all avoidable).

What's the common pattern for testing these kinds of methods?

public function getConfigFromDb()
{
    if (!is_null($this->configInDb)) {
        return $this->configInDb;
    }

    $sql = new Sql($this->getSlaveDbAdapter());

    $select = $sql->select()
                  ->from('mytable');

    $statement = $sql->prepareStatementForSqlObject($select);
    $results   = $statement->execute();
    $results->buffer();

    $this->configInDb = $return;

    return $results;
}
  • 写回答

1条回答 默认 最新

  • dongluo3962 2013-12-13 16:33
    关注

    @Julian you're right, I'll put it as an answer

    In this case, I would add a SqlFactory and register it as a service (in factories param in service manager config), that way you can easily mock the service and the objects you'll get from it.

    To go further on the subject, I delegate all object creation to factories that I can call using ServiceManager. The fact is, that way, I can test my Factory in isolation, injecting all dependencies it needs, asserting that the actual object created is the expected object. And anytime I need an object from Factory in the method tested, I can serve a real instance, or a Mock.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog