mattiasgeniar / phpunit-query-count-assertions
为phpunit定制断言,允许你统计测试中使用的SQL查询数量。可以用来强制执行某些性能特性(例如:限制某个操作的查询数为X)。
1.1.3
2024-03-04 10:05 UTC
Requires
- php: ^7.3|^7.4|^8.0
- illuminate/contracts: ^7.0|^8.0|^9.0|^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^5.0|^6.23|^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.5|^10.5
README
为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)。有关更多信息,请参阅许可文件。