mattiasgeniar/phpunit-query-count-assertions

为phpunit定制断言,允许你统计测试中使用的SQL查询数量。可以用来强制执行某些性能特性(例如:限制某个操作的查询数为X)。

1.1.3 2024-03-04 10:05 UTC

This package is auto-updated.

Last update: 2024-09-04 11:20:34 UTC


README

Tests

为phpunit定制断言,允许你统计测试中使用的SQL查询数量。可以用来强制执行某些性能特性(例如:限制某个操作的查询数为X)。

目前仅适用于Laravel。

安装

您可以通过composer安装此包

composer require --dev mattiasgeniar/phpunit-query-count-assertions

使用方法

AssertsQueryCounts特性添加到测试类中,在setup()中初始化,然后可以开始断言查询。

use Mattiasgeniar\PhpunitQueryCountAssertions\AssertsQueryCounts;

class YourTest extends TestCase
{
    use AssertsQueryCounts;

    public function setUp(): void
    {
        parent::setUp();

        AssertsQueryCounts::trackQueries();
    }

    /** @test */
    public function your_tests_go_here()
    {
        $this->assertNoQueriesExecuted();
    }
}

可用的断言/方法

您可以使用以下方法,其名称应具有自解释性

$this->assertNoQueriesExecuted();       // No queries should have been run

$this->assertQueryCountMatches(5);      // Query count should be exactly 5

$this->assertQueryCountLessThan(6);     // Should be less than 6 queries

$this->assertQueryCountGreaterThan(4);  // Should be more than 4 queries

所有这些方法都可以接受一个闭包作为额外参数。断言将仅考虑闭包中执行的查询。如果您使用这种方式进行测试,您不需要自己调用trackQueries

$this->assertQueryCountMatches(2, function() {
    // assertion will pass if exactly 2 queries happen here.
});

测试

composer test

许可

MIT许可(MIT)。有关更多信息,请参阅许可文件