douhuang9886 2018-11-02 14:05
浏览 122
已采纳

PHPUnit使用数据库连接的模拟函数

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

    }
}
  • 写回答

1条回答 默认 最新

  • dos71253 2018-11-02 14:28
    关注

    You pass the mock to the Task class constructor, but it doesn't do anything with it.

    $task = new Task($resultSetMock);

    Updated the code so that it will be used:

    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;
        }
    
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分