Question

I'm setting up some unit tests for a class that uses Predis to connect to a Redis DB. I'm trying to mock the Client and Connection objects so that I can do the unit test.

This is the section of my class that deals with the Predis Client object:

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!" );
    }
}

This is how I'm trying to set up the unit test:

    $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 );

Inside the unit test, $redis->getConnection() returns the $redisConnection object, but once inside the class I'm unit testing, $redis->getConnection() returns NULL.

Any ideas on what I might be missing?

Was it helpful?

Solution

Probably just need this:

 $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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top