是否有可能使用 PHPUnit 模拟对象来调用一个神奇的 __call() 方法? [英] Is it possible, using PHPUnit mock objects, to expect a call to a magic __call() method?

查看:17
本文介绍了是否有可能使用 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() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆