2009-11-13 113 views
5

我想在PHP和PHPUnit中创建一个模拟对象。到目前为止,我有这样的:在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); 

无视我的可怕分钟暧昧对象名称,我明白我做了什么是
- 创建一个模拟对象,用两种方法来配置,
- 配置'get_events'方法返回一个空白数组,并且将模拟删除到构造函数中。

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

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

或者其他的一些,但是这是行不通的。我应该怎么做?

切线方向,这是否表示我的代码构造不佳,如果我需要配置多个方法来测试?

回答

9

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

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

你已经尝试过了吗?


编辑:

好,做一些代码搜索,我发现了一些例子,可以帮助你走出

入住这example

他们用这样的:

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 => '[email protected]', 
            ), 
             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)); 
(...) 
} 

也许你的问题在别的地方?

让我知道是否有帮助。


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())); 
+0

我曾尝试这一点,这似乎并没有工作。 – 2009-11-13 02:29:09

+0

看起来确实是正确的方法。检查我的编辑。也许还有别的错误?如果你分享一些更完整的代码,也许其他人或我可以提供帮助。 – 2009-11-13 03:00:41

+0

试了一遍,它的工作。谢谢你的帮助! – 2009-11-16 16:39:38