2013-10-25 147 views
0

我正在爲使用Predis連接到Redis數據庫的類設置一些單元測試。我試圖嘲笑Client和Connection對象,以便我可以進行單元測試。PHP嘲笑沒有從模擬函數返回模擬對象

這是我的班,與Predis客戶對象涉及的部分:

public function __construct(Predis\Client $redis = null){ 
    $this->_redis = $redis; 
    $this->_validateConnection(); 
} 

private function _validateConnection(){ 
    $connnection = $this->_redis->getConnection(); 

    // var_dump($connection); -> null 

    if (!$connection->isConnected()){ 
     throw new InvalidDatabase("Unable to connect to the Redis database!"); 
    } 
} 

這是我正在嘗試設置了單元測試:

$redisConnection = m::mock('overload:Predis\Connection\SingleConnectionInterface') 
     ->shouldReceive('isConnected') 
     ->once() 
     ->andReturn(true) 
     ->getMock(); 

    $redis = m::mock("Predis\Client") 
     ->shouldReceive(array('getConnection' => $redisConnection)) 
     ->once() 
     ->getMock(); 

    // var_dump($redis->getConnection()); -> $redisConnection 

    $instance = new Class($redis); 

在單位內測試,$redis->getConnection()返回$redisConnection對象,但一旦進入單元測試階段,$redis->getConnection()返回NULL。

關於我可能會遺漏的任何想法?

回答

1

可能只需要這樣:

$redis = m::mock("Predis\Client") 
    ->shouldReceive(array('getConnection' => $redisConnection)) 
    ->once() 
    ->andReturn('whatever you want to return?') // missing a return... by default it will return null. 
    ->getMock();