2011-10-18 54 views
5

我試圖在PHPUnit測試中模擬出Predis客戶端。當我調用我試圖模擬出的方法時,在測試結束時,PHPUnit告訴我期望沒有得到滿足。爲什麼我的PHPUnit模擬的Predis客戶端不符合我的期望?

下面是重現我的問題代碼示例:

class MockRedisTest extends \PHPUnit_Framework_TestCase { 
private $mockRedis; 

public function testMockRedis() { 

    $mockRedis = $this->getMock('Predis\\Client'); 

    $mockRedis->expects( $this->once()) 
     ->method("exists") 
     ->with($this->equalTo("query-key")) 
     ->will($this->returnValue(true)); 

    $mockRedis->exists("query-key"); 
} 

}

並且PHPUnit會認爲該方法不叫:

1)MockRedisTest :: testMockRedis 預期失敗方法名稱等於被調用1次(s)。方法預計被稱爲1次,實際稱爲0次。

爲什麼?是否因爲Predis客戶端似乎在使用__call來響應匹配redis命令的方法調用?

更新:我得到的印象是它與__call方法有關。更改代碼到這個作品:

public function testMockRedis() { 

    $mockRedis = $this->getMock('Predis\\Client'); 

    $mockRedis->expects( $this->once()) 
     ->method("__call") 
     ->with("exists", $this->equalTo(array("query-key"))) 
     ->will($this->returnValue(true)); 

    $mockRedis->exists("query-key"); 
} 

不知道我對此感到滿意。有沒有更好的方法來模擬使用__call代理方法的類?

回答

8

我認爲你可以使用

$mockRedis = $this->getMock('Predis\\Client', array('exists')); 
// ... 

迫使模擬對象瞭解你的神奇功能。儘管如此,這限制了模擬方法exists()的能力。你必須特別包含所有其他被嘲笑的方法。

+0

完美。謝謝。 –

0

如果你想嘲笑特定的服務器配置文件,並確保你是不是要求的不同的服務器版本的方法,使用

<?php 
$mockRedis = $this->getMock('Predis\\Client', array_keys((new Predis\Profiles\ServerVersion26)->getSupportedCommands())); 
0

對於PHPUnit的5,使用

$this->createPartialMock('Predis\\Client', ['exists']); 

爲了讓您模擬瞭解「存在」方法(或任何其他redis本機命令)

相關問題