Skip to content

Instantly share code, notes, and snippets.

@Jasonej
Last active November 19, 2021 14:24
Show Gist options
  • Save Jasonej/4d76d916a888b4ffe1894782ddd7af32 to your computer and use it in GitHub Desktop.
Save Jasonej/4d76d916a888b4ffe1894782ddd7af32 to your computer and use it in GitHub Desktop.
Resource Testing Concept
<?php
declare(strict_types=1);
namespace Tests\Feature;
use Tests\Asserters\UserResourceAsserter;
use Tests\Asserters\UserStructureAsserter;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_example(): void
{
# Act
$response = $this->getJson('/api/users/1');
# Assert
$response->assertOk();
$response->assertJson(new UserResourceAsserter($user));
$response->assertJson(new UserStructureAsserter);
}
}
<?php
declare(strict_types=1);
namespace Tests\Asserters;
use Closure;
use Illuminate\Testing\Fluent\AssertableJson;
use Sourcetoad\EnhancedResources\Formatting\FormatManager;
abstract class ResourceAsserter
{
protected FormatManager $formatManager;
public function __construct(
protected mixed $resource,
protected ?string $path = null,
) {
$this->formatManager = new FormatManager($this);
}
public function format(string $name): static
{
$this->formatManager->select($name);
return $this;
}
public function __invoke(AssertableJson $json): void
{
if ($this->path) {
$json->has($this->path, Closure::fromCallable([$this, 'performAssertions']));
return;
}
$this->performAssertions($json);
}
protected function performAssertions(AssertableJson $json): void
{
$this->formatManager->current()->reflection()->invoke($this, $json);
}
}
<?php
declare(strict_types=1);
namespace Tests\Asserters;
use App\Models\User;
use Illuminate\Testing\Fluent\AssertableJson;
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format;
/** @property-read User $resource */
class UserResourceAsserter extends ResourceAsserter
{
#[Format('base')]
public function base(AssertableJson $json): void
{
$json->where('created_at', $this->resource->created_at?->toIso8601ZuluString())
->where('email_address', $this->resource->email_address)
->where('first_name', $this->resource->first_name)
->where('id', $this->resource->getRouteKey())
->where('last_name', $this->resource->last_name)
->where('role', $this->resource->role->value)
->where('updated_at', $this->resource->updated_at?->toIso8601ZuluString());
}
}
<?php
declare(strict_types=1);
namespace Tests\Asserters;
use Illuminate\Testing\Fluent\AssertableJson;
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format;
class UserStructureAsserter extends ResourceAsserter
{
#[Format('base')]
public function base(AssertableJson $json): void
{
$json->has('created_at')
->has('email_address')
->has('first_name')
->has('id')
->has('last_name')
->has('role')
->has('updated_at');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment