【问题标题】:PHPUnit Doctrine Repository magic methodsPHPUnit Doctrine Repository 魔法方法
【发布时间】:2018-08-21 17:56:35
【问题描述】:

我需要一些帮助来全面测试依赖于 Doctrine 的课程。

我的班级中有一个方法使用 Doctrine EntityRepository 中的 magic 方法 findOneBy...,如下所示:

但是当我运行我的测试时,我总是有这个警告:

如何模拟该调用?下面我介绍了 EntityManager 魔术 __call 方法应该如何工作:

【问题讨论】:

  • 您的字段名称是什么,或者您可以显示您的实体吗?
  • setMethods 可用于向模拟对象添加方法。 phpunit.de/manual/current/en/test-doubles.html
  • 该字段的名称是 $idShopUrl,在运行代码中它很好,没有任何问题,但我想知道如何模拟/测试它

标签: symfony doctrine-orm phpunit tdd


【解决方案1】:

您可以模拟在调用无法访问的方法时调用的魔术方法__call

$mock
    ->expects($this->once())
    ->method('__call')
   ->with(
      $this->equalTo('findOneByIdShopUrl'), //
      $this->equalTo(['5'])
   )
   ->willReturn(['shop' => 'shop info']); // return shop object

也检查http://php.net/manual/en/language.oop5.overloading.php#object.call

另一种选择是使用setMethods()

$this->getMockBuilder('ShopRepository')->setMethods(['findOneByShopId'])->getMock(); 

然后是其余的逻辑,如 will、with 等方法。

【讨论】:

【解决方案2】:

我认为你可以用真正的方法 findOneBy(array('XXXX' => 'identifier')) 替换魔术方法 findOneByXXXX('identifier')。

也就是说:

$this->shopUrlRepository->findOneByIdShopUrl($this->shop->getId());

收件人:

$this->shopUrlRepository->findOneBy(array('IdShopUrl' => $this->shop->getId()));

这是一个真正的方法。 Doctrine documentation

希望对你有帮助。

【讨论】:

  • 两种情况都有效,但在那种情况下对我来说重要的是如何模拟它的知识:)
猜你喜欢
  • 2021-02-12
  • 2012-11-07
  • 2014-10-07
  • 1970-01-01
  • 2014-12-14
  • 2015-02-12
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
相关资源
最近更新 更多