我想测试连接到数据库,并且我有一个测试:
$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);
这是数据库类:
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;
}
}
}
但显然getAuthorDb方法不是模拟的。它是reak数据。为什么?!
请帮助
答案 0 :(得分:0)
调用new DB
时,您是在创建真实的类,而不是在模拟的类。您必须将模拟的数据库实例传递给正在使用它的任何类或函数。
要记住的重要一点是,模拟类仍然是类,您不会在全局范围内替换名称DB
。您必须在其他地方使用模拟的类,否则它就坐在那里。