0

我正在为使用 Predis 连接到 Redis DB 的类设置一些单元测试。我正在尝试模拟 Client 和 Connection 对象,以便进行单元测试。

这是我的课程中处理 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。

关于我可能遗漏的任何想法?

4

1 回答 1

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();
于 2014-02-28T20:25:53.460 回答