我正在为使用Predis连接到Redis DB的类设置一些单元测试。我正在尝试模拟Client和Connection对象,以便我可以进行单元测试。
这是我的类中处理Predis Client对象的部分:
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。
关于我可能遗失的任何想法?
答案 0 :(得分: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();