Is it possible, using PHPUnit mock objects, to expect a call to a magic __call() method?(是否有可能使用 PHPUnit 模拟对象来调用一个神奇的 __call() 方法?)
问题描述
我在测试中有一个模拟对象.真实对象 PageRepository 使用 __call() 实现了一个神奇的方法,因此如果您调用 $pageRepository->findOneByXXXX($value_of_field_XXXX),它将在数据库中搜索与该参数匹配的记录.
I've got a mock object in a test. The real object, PageRepository, implements a magic method using __call(), so if you call $pageRepository->findOneByXXXX($value_of_field_XXXX), it will search the database for records matching that parameter.
有没有办法模拟那个方法?
Is there a way to mock that method?
真正的方法调用看起来像这样:
The real method call would look something like this:
$homepage = $pageRepository->findOneBySlug('homepage');
测试看起来像这样:
$mockPageRepository->expects($this->any())
->method('findOneBySlug')
->will($this->returnValue(new Page()));
但它不起作用——PHPUnit 没有发现方法调用.让它看到方法的唯一方法是在 PageRepository 中显式定义方法.
But it doesn't work -- PHPUnit doesn't spot the method call. The only way to get it to see the method is to define the method explicitly in PageRepository.
推荐答案
PHPUnit 的 getMock()
接受第二个参数,一个包含要模拟的方法名称的数组.如果您在此数组中包含方法名称,则模拟对象将包含具有该名称的方法,expects()
和朋友将使用该方法.
PHPUnit's getMock()
takes a second argument, an array with the names of methods to be mocked.
If you include a method name in this array, the mock object will contain a method with that name, which expects()
and friends will work on.
这甚至适用于未在真实"类中定义的方法,因此类似以下的方法应该可以解决问题:
This applies even for methods that are not defined in the "real" class, so something like the following should do the trick:
$mockPageRepository = $this->getMock('PageRepository', array('findOneBySlug'));
请记住,您必须明确包含任何其他也需要模拟的方法,因为只有数组中命名的方法是为模拟对象定义的.
Keep in mind that you'll have to explicitly include any other methods that also need to be mocked, since only the methods named in the array are defined for the mock object.
这篇关于是否有可能使用 PHPUnit 模拟对象来调用一个神奇的 __call() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有可能使用 PHPUnit 模拟对象来调用一个神奇的 __call() 方法?


- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01