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

查看:82
本文介绍了使用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.

这甚至适用于未在"real"类中定义的方法,因此应使用类似以下内容的方法:

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'));

请记住,您必须显式包括也需要模拟的其他任何方法,因为 only 数组中命名的方法是为模拟对象定义的.

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天全站免登陆