[英]phpunit test with PDO mock
i am trying to test a class with two methods. 我试图用两种方法测试一个类。 both interact with a database which is the why im am trying to work with PDO mock object.
两者都与数据库交互,这就是为什么我要使用PDO模拟对象的原因。 I couldn't find much documentation about mocking PDO object and working with them but after following one tutorial that looked pretty close to what i need i ended up with a PDO mock object, but i don't understand how should i use it.
我找不到有关模拟PDO对象以及如何使用它们的大量文档,但是在遵循了一个看起来与我的需求非常接近的教程之后,我最终得到了一个PDO模拟对象,但是我不知道该如何使用它。
to make thing simple this is my class with the first method i want to test: 为了简单起见,这是我要测试的第一个方法的类:
<?php
use Slim\Slim;
class AdProviders {
public $providers = null;
protected $db = null;
function __construct() {
}
function getDbh() {
if ($this->db === null){
$this->db = Slim::getInstance()->db;
}
return $this->db->getConnection();
}
}
and according to the db schema this is how i created the PDO object: 根据数据库模式,这就是我创建PDO对象的方式:
<?php
require dirname(__FILE__).'/../../src/vendor/autoload.php';
class AdProvidersTest extends PHPUnit_Framework_TestCase
{
public function dataProvider()
{
return array (
array (1, '1st', 'desc_1', 11),
array (2, '2nd', 'desc_2', 22),
array (3, '3rd', 'desc_3', 33),
);
}
/**
* @dataProvider dataProvider
*/
public function testAdProviders($id, $name, $desc, $account_id)
{
$data = array (
array (
'id' => $id,
'name' => $name,
'description' => $desc,
'account_id' => $account_id
)
);
$stmt = $this->getMock('PDOStatement', array ('fetchAll'));
$stmt->expects($this->any())
->method('fetchAll')
->will($this->returnValue($data));
$pdo = $this->getMock('PDO', array('prepare'),
array('sqlite:dbname=:memory'),'PDOMock_' . uniqid(),true);
$pdo->expects($this->any())
->method('prepare')
->will($this->returnValue($stmt));
}
}
Now i am really lost with how should i test the getDbh()
method ... is this the correct way to create a PDO mock for the purpose of my test? 现在我真的迷失了我应该如何测试
getDbh()
方法...这是出于测试目的而创建PDO模拟的正确方法吗? and if so, how can i use it to test the method? 如果是这样,我如何使用它来测试该方法?
any kind of guidance will be highly appreciated... thx 任何形式的指导将不胜感激... thx
You need to inject this mock into Slim::getInstance() that is why it is bad to use singletons and better to use dependency injection pattern. 您需要将此模拟注入Slim :: getInstance(),这就是为什么使用单例不好而更好地使用依赖项注入模式的原因。
It is kind a senseless to mock PDO where you can't change PDO in Slim::getInstance()->db
在无法在
Slim::getInstance()->db
更改PDO的情况下模拟PDO是一种毫无意义的事情
What you really may test here is whether method getDbh() returns instance of Connection. 您真正可以在此处测试的是方法getDbh()是否返回Connection的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.