diff --git a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php index c0f8dfb3d589..93a396b250ba 100644 --- a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php +++ b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php @@ -5,6 +5,7 @@ use Illuminate\Contracts\Support\Jsonable; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Events\QueryExecuted; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Testing\Constraints\CountInDatabase; @@ -177,15 +178,21 @@ protected function assertModelMissing($model) */ public function expectsDatabaseQueryCount($expected, $connection = null) { - with($this->getConnection($connection), function ($connection) use ($expected) { + with($this->getConnection($connection), function ($connectionInstance) use ($expected, $connection) { $actual = 0; - $connection->listen(function () use (&$actual) { - $actual++; + $connectionInstance->listen(function (QueryExecuted $event) use (&$actual, $connectionInstance, $connection) { + if (is_null($connection) || $connectionInstance === $event->connection) { + $actual++; + } }); - $this->beforeApplicationDestroyed(function () use (&$actual, $expected, $connection) { - $this->assertSame($actual, $expected, "Expected {$expected} database queries on the [{$connection->getName()}] connection. {$actual} occurred."); + $this->beforeApplicationDestroyed(function () use (&$actual, $expected, $connectionInstance) { + $this->assertSame( + $actual, + $expected, + "Expected {$expected} database queries on the [{$connectionInstance->getName()}] connection. {$actual} occurred." + ); }); }); diff --git a/tests/Foundation/FoundationInteractsWithDatabaseTest.php b/tests/Foundation/FoundationInteractsWithDatabaseTest.php index ce6c296bb4a0..1fd173f62e55 100644 --- a/tests/Foundation/FoundationInteractsWithDatabaseTest.php +++ b/tests/Foundation/FoundationInteractsWithDatabaseTest.php @@ -385,6 +385,31 @@ public function testExpectsDatabaseQueryCount() } catch (ExpectationFailedException $e) { $this->assertSame("Expected 3 database queries on the [testing] connection. 4 occurred.\nFailed asserting that 3 is identical to 4.", $e->getMessage()); } + + $case = new class extends TestingTestCase + { + use CreatesApplication; + + public function testExpectsDatabaseQueryCount() + { + $this->expectsDatabaseQueryCount(4); + $this->expectsDatabaseQueryCount(1, 'mysql'); + + DB::pretend(function ($db) { + $db->table('foo')->count(); + $db->table('foo')->count(); + $db->table('foo')->count(); + }); + + DB::connection('mysql')->pretend(function ($db) { + $db->table('foo')->count(); + }); + } + }; + + $case->setUp(); + $case->testExpectsDatabaseQueryCount(); + $case->tearDown(); } protected function mockCountBuilder($countResult, $deletedAtColumn = 'deleted_at')