현재 위치: > 최신 기사 목록> STMT_INIT를 포함하는 데이터베이스 방법을 단위 테스트하는 방법

STMT_INIT를 포함하는 데이터베이스 방법을 단위 테스트하는 방법

M66 2025-05-17

PHP 개발 중에 데이터베이스 작업에 MySQLI 확장을 사용하는 것이 일반적입니다. mysqli :: stmt_init 함수는 전처리 문을 초기화하는 데 사용되며, 이는 SQL 쿼리의 보안 및 효율성을 향상시키는 데 매우 중요합니다. 그러나 단위 테스트를 수행 할 때 데이터베이스 연결이 존재하기 때문에 MySQLI :: STMT_INIT 기능을 포함하는 데이터베이스 작업 방법을 효과적으로 테스트하는 방법은 어려운 문제가됩니다.

이 기사는 PHP의 단위 테스트 방법, 특히 MySQLI :: STMT_INIT를 포함하는 데이터베이스 작동 방법을 테스트하는 방법을 소개합니다. PHP의 장치 테스트 프레임 워크 인 PHPUNIT를 사용하고 일부 모의 개체 및 데이터베이스 시뮬레이션 도구를 결합하여 데이터베이스 작업을 시뮬레이션하고 데이터베이스와 직접 상호 작용하지 않습니다.

1. 데이터베이스 작업 클래스를 만듭니다

먼저 mysqli :: stmt_init을 사용하여 데이터베이스 작동 방법이 포함 된 간단한 데이터베이스 작동 클래스를 만듭니다. 코드 예제는 다음과 같습니다.

 <?php
class Database
{
    private $connection;

    public function __construct($host, $username, $password, $dbname)
    {
        $this->connection = new mysqli($host, $username, $password, $dbname);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

    public function prepareAndExecute($query, $params)
    {
        $stmt = $this->connection->stmt_init();

        if ($stmt->prepare($query)) {
            $stmt->bind_param(...$params);
            $stmt->execute();
            return $stmt->get_result();
        } else {
            throw new Exception('Query preparation failed');
        }
    }
}

이 클래스에서는 repareendexecute 메소드가 mysqli :: stmt_init 함수를 사용하여 전처리 명령문을 초기화하고 들어오는 SQL 쿼리를 실행합니다.

2. 단위 테스트를 작성하십시오

이 데이터베이스 작동 클래스를 테스트하려면 mysqli :: stmt_init 함수 및 관련 데이터베이스 작업을 시뮬레이션해야합니다. 우리는 PhPunit과 Mockery를 사용하여 테스트하는 동안 실제 데이터베이스 상호 작용을 피하기 위해 조롱 된 MySQLI 객체를 만듭니다.

단위 테스트 코드는 다음과 같습니다.

 <?php
use PHPUnit\Framework\TestCase;
use Mockery;

class DatabaseTest extends TestCase
{
    private $db;
    private $mockConnection;

    public function setUp(): void
    {
        $this->mockConnection = Mockery::mock('mysqli');
        $this->db = new Database('localhost', 'user', 'password', 'test_db');
        $this->db->connection = $this->mockConnection;
    }

    public function testPrepareAndExecute()
    {
        // Mock stmt_init to return a mocked statement object
        $mockStmt = Mockery::mock('mysqli_stmt');
        $this->mockConnection->shouldReceive('stmt_init')->once()->andReturn($mockStmt);

        // Mock the prepare method to return true
        $mockStmt->shouldReceive('prepare')->once()->andReturn(true);
        $mockStmt->shouldReceive('bind_param')->once();
        $mockStmt->shouldReceive('execute')->once();
        $mockStmt->shouldReceive('get_result')->once()->andReturn(true);

        // Call the method
        $result = $this->db->prepareAndExecute('SELECT * FROM users WHERE id = ?', ['i', 1]);

        // Assert that the result is true
        $this->assertTrue($result);
    }

    public function tearDown(): void
    {
        Mockery::close();
    }
}

이 테스트에서는 Mockery를 사용하여 MySQLIMySQLI_STMT 객체를 시뮬레이션하고 PreparenExecute 메소드가 준비 , BIND_PARAM , EXECUTE 및 기타 작업을 올바르게 수행하는지 확인합니다.

3. 테스트를 실행하십시오

phpunit 및 mockery가 설치되어 있는지 확인하십시오. 다음 명령을 통해 설치할 수 있습니다.

 composer require --dev phpunit/phpunit mockery/mockery

그런 다음 테스트를 실행할 수 있습니다.

 php vendor/bin/phpunit DatabaseTest.php

테스트가 통과되면 다음과 유사한 메시지가 표시됩니다.

 OK (1 test, 1 assertion)

4. 결론

Mock Object와 PhPunit 프레임 워크를 사용하면 실제 데이터베이스와 상호 작용하지 않고 MySQLI :: STMT_INIT를 포함하는 데이터베이스 작동 방법을 효과적으로 테스트 할 수 있습니다. 이를 통해 단위 테스트에서 데이터베이스의 가용성에 대한 의존성을 피하면서 데이터베이스 작동 로직의 정확성을 보장 할 수 있습니다.

위의 것은 mysqli :: stmt_init 함수를 포함하는 데이터베이스 작동 방법을 단위 테스트하는 방법에 대한 소개입니다. 이 기사가 도움을 줄 수 있고 PHP 장치 테스트를보다 효율적으로 수행 할 수 있기를 바랍니다.

관련 링크