1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-04 16:44:04 +00:00

Add TenancyTestCase base class for tenant-aware test initialization and central context support

- Adds a reusable base test case to simplify writing tenant-aware tests
- Automatically initializes tenancy using TEST_TENANT from config or .env.testing
- Provides `runInCentralContext()` to temporarily switch to central DB context
- Improves test reliability and consistency for multi-tenant applications
This commit is contained in:
lokeshrangani 2025-05-12 19:00:54 +05:30
parent d98a170fbd
commit cf5ec0be6d
2 changed files with 73 additions and 0 deletions

View file

@ -196,4 +196,6 @@ return [
'--class' => 'DatabaseSeeder', // root seeder class '--class' => 'DatabaseSeeder', // root seeder class
// '--force' => true, // This needs to be true to seed tenant databases in production // '--force' => true, // This needs to be true to seed tenant databases in production
], ],
'test_tenant' => env('TEST_TENANT', 1),
]; ];

View file

@ -0,0 +1,71 @@
<?php
namespace Stancl\Tenancy\Testing;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TenantAwareTestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Set this to true in child classes to enable tenancy.
*
* @var bool
*/
protected bool $tenancy = true;
/**
* Tenant instance used in the test.
*
* @var \App\Models\Tenant|null
*/
protected ?Tenant $tenant = null;
protected function setUp(): void
{
parent::setUp();
if ($this->tenancy) {
$this->initializeTenancy();
}
}
/**
* Initialize tenancy for a specific tenant.
*
* @param string|int|null $tenantIdentifier
* @return void
*/
protected function initializeTenancy(string|int|null $tenantIdentifier = null): void
{
$identifier = $tenantIdentifier ?? config('tenancy.test_tenant');
$this->tenant = Tenant::find($identifier);
if (! $this->tenant) {
$this->fail("Tenant [{$identifier}] not found. Please ensure TEST_TENANT is set correctly in .env.testing or config('tenancy.test_tenant').");
}
tenancy()->initialize($this->tenant);
}
/**
* Run assertions or actions in central context.
*/
protected function runInCentralContext(callable $callback): mixed
{
$tenant = $this->tenant ?? tenancy()->tenant;
tenancy()->end();
try {
return $callback();
} finally {
if ($tenant) {
tenancy()->initialize($tenant);
}
}
}
}