7

我正在尝试在 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);

暂时忽略我令人毛骨悚然的模棱两可的对象名称,我知道我所做的是
- 创建了一个模拟对象,具有 2 个配置方法,
- 配置了“get_events”方法以返回一个空白数组,以及
- 将模拟放入构造函数。

我现在想做的是配置第二种方法,但我找不到任何解释如何做到这一点的东西。我想做类似的事情

$object
    ->expects($this->once())
    ->method('get_events')
    ->will($this->returnValue(array()))
    ->expects($this->once())
    ->method('set_properties')
    ->with($this->equalTo(array()))

或类似的,但这不起作用。我该怎么做?

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

4

1 回答 1

12

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

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

你已经试过了吗?


编辑:

好的,通过进行一些代码搜索,我找到了一些可能对您有所帮助的示例

检查这个例子

他们像这样使用它:

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));
(...)
}

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

让我知道这是否有帮助。


编辑2:

你可以试试这个:

$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()));
于 2009-11-13T02:14:51.407 回答