使用数据库连接的PHPUnit模拟功能

时间:2018-11-02 14:05:53

标签: php mocking phpunit

我是使用PHPUnit的新手,我正在尝试测试功能getAllTask​​s(),该功能需要从数据库中获取所有任务。我尝试了一切,但我只是在使代码更糟。因此,请帮助我解决问题。 TaskTest.php是我尝试进行测试的东西,但没有用。并且确定是否有做某事的更好方法,我也喜欢学习新知识。这是我的代码:

编辑:我更改了TaskTest.php的代码,并设法通过了测试。有人可以告诉我这是测试此功能的好方法还是更好的方法?谢谢!

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]);

    }
}

1 个答案:

答案 0 :(得分:0)

您将模拟传递给Task类构造函数,但它对此没有任何作用。

$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;
    }

    // ...
}