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:
EDIT: 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!
Task.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;
}
}
Database.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
<?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]);
}
}