首页 > 编程语言 >php unit 的使用

php unit 的使用

时间:2023-02-02 18:12:03浏览次数:64  
标签:code msg query 使用 test new php id unit

安装步骤,参见以下链接:

https://www.cnblogs.com/lxz88/p/6264463.html

1: 新建文件user case 

 

 

namespace Domain\Test\UseCase;

use Domain\UseCase;
use  Domain\UseCaseInterface;
use InvalidArgumentException;
use PDO;
use Shared\Json;
use Exception;


class AddTest extends UseCase implements UseCaseInterface
{

    public function execute(array $data)
    {
        if (!isset($data['test_code'])) {
            throw new InvalidArgumentException('test_code not provided');
        } 
        $query = $this->db->prepare("
                INSERT INTO phpUnit_test ( test_name,test_code)
                VALUES (
                            :test_name,
                            :test_code
                        )");

        $query->bindParam(':test_name', $data['test_name'], PDO::PARAM_STR);
        $query->bindParam(':test_code', $data['test_code'], PDO::PARAM_STR);

        if (!$query->execute()) {
            throw new Exception(Json::errorInfo($query));
        }

        $new_id = $this->db->lastInsertId();

        return [
            'test_id' => $new_id,
        ];
    }
}

2.在phpunit /文件下新建 文件名+Test.php

 

 

 

 

 

 文件代码:

<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use Domain\Test\UseCase\AddTest;
use Domain\Test\UseCase\GetTestCode;
use Domain\Test\UseCase\DeleteTest;

final class TrainingTest extends TestCase
{
    private static $db;

    // 数据库
    public static function setUpBeforeClass(): void
    {
        require __DIR__ . '/../../../../config/_config.inc.php';
        require __DIR__ . '/db.php';

        self::$db->query("SET @eamic_user = 'PHPUnit';");
    }

    public function testAddtest(): void
    {

        global $DB_connection_admin;

        $test = new AddTest(self::$db);
        $msg = $test->execute([
            'test_code' => 'E' . Date('mdhis'),
            'test_name' => 'PHPUnit' . Date('mdhis'),
        ]);
// 返回的ID应该大于0
        $this->assertGreaterThan(0, $msg['test_id']);
    }

    public function testGetTestcode(): void
    {
        $test = new GetTestCode(self::$db);
        $msg = $test->execute([
            'test_id' => 9
        ]);

        // 应该得到东西
        $this->assertArrayHasKey('test_id', $msg);
        $this->assertArrayHasKey('test_code', $msg);
    }

    public function testDeleteTest(): void
    {

        $test=new DeleteTest(self::$db);
        $msg = $test->execute([
            'test_id' => 24
        ]);
 // 受影响行应该等于1
        $this->assertEquals(1, $msg['rowCount']);
    }

}

终端输入:切换到 test 目录

phpunit 终端命令:

 

phpunit-watcher watch --filter=TrainingTest

 

标签:code,msg,query,使用,test,new,php,id,unit
From: https://www.cnblogs.com/xiaoyantongxue/p/17086930.html

相关文章