使用数据库连接的 PHPUnit 模拟函数 [英] PHPUnit Mocking functions which use Database Connection
问题描述
我是 PHPUnit 的新手,我正在尝试测试需要从数据库中获取所有任务的函数 getAllTasks().我尝试了一切,但我只是让我的代码更糟.所以请帮我解决这个问题.TaskTest.php 是我试图进行测试但它不起作用的东西.并且确定是否有更好的方法来做某事,我也喜欢学习新东西.这是我的代码:
I am new to using PHPUnit and i am trying to test function getAllTasks() which need to fetch all tasks from database. I tried everything but i am just making my code worse. So please help me to solve the problem. TaskTest.php is something i tried to make test but it dont works. And sure if there are better ways to do something, i like to learn new stuff too. Here is my code:
我更改了 TaskTest.php 的代码,并设法通过了测试.有人可以告诉我这是否是测试此功能的好方法,或者有更好的方法吗?谢谢!
I changed code for TaskTest.php and i managed to get test pass. Can someone please tell me if this is good way to test this function, or there are better ways? Thanks!
任务.php
<?php
require_once 'Database.php';
class Task {
private $db;
public function __construct() {
$this->db = new Database;
}
public function getAllTasks() {
$this->db->query('SELECT * FROM tasks');
$results = $this->db->resultSet();
return $results;
}
}
数据库.php
<?php
class Database {
private $host = 'localhost';
private $user = 'root';
private $pass = '123456';
private $dbname = 'todolist';
private $dbh;
private $stmt;
private $error;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create PDO instance
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch(PDOException $e){
$this->error = $e->getMessage();
echo $this->error;
}
}
public function query($sql){
$this->stmt = $this->dbh->prepare($sql);
$this->execute();
}
public function execute(){
return $this->stmt->execute();
}
public function resultSet(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
TaskTest.php
TaskTest.php
<?php
require_once './src/Task.php';
require_once './src/Database.php';
use PHPUnit\Framework\TestCase;
class TaskTest extends TestCase {
public function testGetAllTasks() {
$table = array(
array(
'task_id' => '1',
'task_desc' => 'Task One Test'
),
array(
'task_id' => '2',
'task_desc' => 'Task Two Test'
)
);
$dbase = $this->getMockBuilder('Database')
->getMock();
$dbase->method('resultSet')
->will($this->returnValue($table));
$expectedResult = [
'task_id' => '1',
'task_desc' => 'Task One Test',
];
$task = new Task();
$actualResult = $task->getAllTasks();
$this->assertEquals($expectedResult, $actualResult[0]);
}
}
推荐答案
您将模拟传递给 Task
类构造函数,但它不会对它做任何事情.
You pass the mock to the Task
class constructor, but it doesn't do anything with it.
$task = new Task($resultSetMock);
更新了代码以便使用:
class Task {
private $db;
public function __construct( ?Database $db = null ) {
// set the db if none is provided
if( is_null($db) )
{
$db = new Database;
}
$this->db = $db;
}
// ...
}
这篇关于使用数据库连接的 PHPUnit 模拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!