incr/tests/Feature/CounterTest.php

125 lines
3.2 KiB
PHP
Raw Normal View History

2026-08-15 15:10:26 +02:00
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\Tracker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class CounterTest extends TestCase
{
use RefreshDatabase;
private function tracker(int $count = 0): Tracker
{
return Tracker::factory()->create(['count' => $count]);
}
public function test_increment_adds_exactly_one(): void
{
$tracker = $this->tracker(5);
$response = $this->postJson('/increment');
$response->assertOk()->assertJson(['count' => 6]);
$this->assertSame(6, $tracker->refresh()->count);
}
public function test_increments_accumulate(): void
{
$tracker = $this->tracker();
$this->postJson('/increment');
$this->postJson('/increment');
$this->postJson('/increment');
$this->assertSame(3, $tracker->refresh()->count);
}
public function test_increment_returns_404_without_a_tracker(): void
{
$this->postJson('/increment')->assertNotFound();
}
public function test_count_can_be_set_to_an_absolute_value(): void
{
$tracker = $this->tracker(3);
$response = $this->patchJson('/count', ['count' => 250]);
$response->assertOk()->assertJson(['count' => 250]);
$this->assertSame(250, $tracker->refresh()->count);
}
public function test_count_can_be_set_to_zero(): void
{
$tracker = $this->tracker(42);
$this->patchJson('/count', ['count' => 0])->assertOk();
$this->assertSame(0, $tracker->refresh()->count);
}
/**
* @return array<string, array{mixed}>
*/
public static function invalidCounts(): array
{
return [
'negative' => [-1],
'non-numeric string' => ['abc'],
'fractional' => [1.5],
'above unsigned int ceiling' => [4294967296],
];
}
#[DataProvider('invalidCounts')]
public function test_count_rejects_invalid_values(mixed $value): void
{
$tracker = $this->tracker(7);
$this->patchJson('/count', ['count' => $value])
->assertStatus(422)
->assertJsonValidationErrors('count');
$this->assertSame(7, $tracker->refresh()->count);
}
public function test_count_requires_a_value(): void
{
$this->tracker();
$this->patchJson('/count', [])
->assertStatus(422)
->assertJsonValidationErrors('count');
}
public function test_count_returns_404_without_a_tracker(): void
{
$this->patchJson('/count', ['count' => 5])->assertNotFound();
}
public function test_counter_endpoints_return_json_not_redirects(): void
{
$this->tracker();
$this->postJson('/increment')
->assertOk()
->assertHeader('content-type', 'application/json');
$this->patchJson('/count', ['count' => 1])
->assertOk()
->assertHeader('content-type', 'application/json');
}
public function test_count_is_cast_to_an_integer(): void
{
$this->tracker(12);
$this->assertSame(12, Tracker::first()->count);
}
}