duanba5777 2019-03-20 07:33
浏览 32

不能用mockery phpunit来模拟对象

I want to test connect to data base, and i have a test:

$author=['db_host'=>'a','db_name'=>DB_NAME,'db_user'=>DB_USER,'db_pass'=>DB_PASS,'db_timeout'=>DB_TIMEOUT];    

$mock_db=\Mockery::mock('DB')->makePartial();
$mock_db->shouldReceive('getAuthorDb')->andReturn($author);
$mock_ctrl= new DB;
$mock_ctrl->getAuthorDb=$mock_db;
$result=$mock_ctrl->getConnect();
$this->assertNotNull($result);

and this is DB class:

class DB
{
    public $obj = null;
    public $table = 'contacts';
    public function __construct(){
        $this->getConnect();        
    }
    public function getAuthorDb(){
        return ['db_host'=>HOST,'db_name'=>DB_NAME,'db_user'=>DB_USER,'db_pass'=>DB_PASS,'db_timeout'=>DB_TIMEOUT];
    }
    public function getConnect(){
        try{
            $author=$this->getAuthorDb();
            $dsn="mysql:host=".$author['db_host']."; dbname=".$author['db_name'];
            $this->obj = new \PDO($dsn, $author['db_user'], $author['db_pass'],$author['db_timeout']);
            $this->obj->query("set names 'utf8' ");
        }
        catch(\Exception $e)
        {
            echo $e->getMessage();  exit;
        }
    }
}

but apparently the getAuthorDb method is not mock. it is reak data. Why?!

Please help

  • 写回答

1条回答 默认 最新

  • dove2199 2019-03-28 13:30
    关注

    When you call new DB you're creating the real class and not the mocked one. You'll have to pass your mocked db instance to whatever class or function is using it.
    The important thing to remember is that mocked classes are still classes, you're not replacing the name DB globally or anything. You must use the mocked class somewhere otherwise it's just sitting there.

    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗