在PHPUnit模拟对象中配置多个方法

TR.*_*TR. 6 php phpunit

我试图在PHP和PHPUnit中创建一个模拟对象.到目前为止,我有这个:

$object = $this->getMock('object',
                         array('set_properties',
                               'get_events'),
                         array(),
                         'object_test',
                         null);

$object
    ->expects($this->once())
    ->method('get_events')
    ->will($this->returnValue(array()));

$mo = new multiple_object($object);
Run Code Online (Sandbox Code Playgroud)

忽略了我那些可怕的不明确的对象名称,我明白我所做的是
- 创建一个模拟对象,配置2个方法,
- 配置'get_events'方法返回一个空白数组,并
- 将模拟放入构造函数.

我现在要做的是配置第二种方法,但我找不到任何解释如何做的事情.我想做点什么

$object
    ->expects($this->once())
    ->method('get_events')
    ->will($this->returnValue(array()))
    ->expects($this->once())
    ->method('set_properties')
    ->with($this->equalTo(array()))
Run Code Online (Sandbox Code Playgroud)

或者其他一些,但这不起作用.我该怎么办?

切线,这是否表明我的代码结构很差,如果我需要配置多个方法来测试?

Car*_*ima 11

我对PHPUnit没有任何经验,但我的猜测是这样的:

$object
  ->expects($this->once())
  ->method('get_events')
  ->will($this->returnValue(array()));
$object
  ->expects($this->once())
  ->method('set_properties')
  ->with($this->equalTo(array()));
Run Code Online (Sandbox Code Playgroud)

你有没试过吗?


编辑:

好的,通过一些代码搜索,我发现了一些可能对你有帮助的例子

检查此示例

他们像这样使用它:

public function testMailForUidOrMail()
{
    $ldap = $this->getMock('Horde_Kolab_Server_ldap', array('_getAttributes',
                                                            '_search', '_count',
                                                            '_firstEntry'));
    $ldap->expects($this->any())
        ->method('_getAttributes')
        ->will($this->returnValue(array (
                                      'mail' =>
                                      array (
                                          'count' => 1,
                                          0 => 'wrobel@example.org',
                                      ),
                                      0 => 'mail',
                                      'count' => 1)));
    $ldap->expects($this->any())
        ->method('_search')
        ->will($this->returnValue('cn=Gunnar Wrobel,dc=example,dc=org'));
    $ldap->expects($this->any())
        ->method('_count')
        ->will($this->returnValue(1));
    $ldap->expects($this->any())
        ->method('_firstEntry')
        ->will($this->returnValue(1));
(...)
}
Run Code Online (Sandbox Code Playgroud)

也许你的问题出在其他地方?

如果有帮助,请告诉我.


EDIT2:

你能试试这个:

$object = $this->getMock('object', array('set_properties','get_events'));

$object
  ->expects($this->once())
  ->method('get_events')
  ->will($this->returnValue(array()));
$object
  ->expects($this->once())
  ->method('set_properties')
  ->with($this->equalTo(array()));
Run Code Online (Sandbox Code Playgroud)