是否有可能使用 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.
相关文章