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
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.