From 3880aa27fec3e3bb4c24d9c526fcd56c4153f557 Mon Sep 17 00:00:00 2001 From: Mohammad Alavi Date: Wed, 12 Jul 2023 21:09:26 +0330 Subject: [PATCH] feat: add `assertDatabaseTable` test assertion method --- .../PhpUnit/TestAssertionHelperTrait.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Traits/TestTraits/PhpUnit/TestAssertionHelperTrait.php b/Traits/TestTraits/PhpUnit/TestAssertionHelperTrait.php index 0a8aa846f..3b408614e 100644 --- a/Traits/TestTraits/PhpUnit/TestAssertionHelperTrait.php +++ b/Traits/TestTraits/PhpUnit/TestAssertionHelperTrait.php @@ -5,6 +5,7 @@ use Apiato\Core\Abstracts\Models\Model; use Illuminate\Auth\Access\Gate; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Schema; use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\MockObject\MockObject; @@ -57,4 +58,21 @@ protected function inIds($id, Collection $collection): bool { return in_array($id, $collection->map(fn ($item) => $item->getHashedKey())->toArray()); } + + /** + * Assert if the given database table has the expected columns with the expected types. + * + * @param string $table The table name. + * @param array $expectedColumns The key is the column name and the value is the column type. + * + * Example: $this->assertDatabaseTable('users', ['id' => 'bigint']); + */ + protected function assertDatabaseTable(string $table, array $expectedColumns): void + { + $this->assertSameSize($expectedColumns, Schema::getColumnListing($table), "Column count mismatch for '$table' table."); + foreach ($expectedColumns as $column => $type) { + $this->assertTrue(Schema::hasColumn($table, $column), "Column '$column' not found in '$table' table."); + $this->assertEquals($type, Schema::getColumnType($table, $column), "Column '$column' in '$table' table does not match expected $type type."); + } + } }