【问题标题】:PHP Mockery not returning mocked object from mocked functionPHP Mockery 没有从模拟函数返回模拟对象
【发布时间】:2013-11-04 00:00:19
【问题描述】:

我正在为一个使用 Predis 连接到 Redis 数据库的类设置一些单元测试。我正在尝试模拟 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。

关于我可能缺少什么的任何想法?

【问题讨论】:

    标签: php unit-testing mockery


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多