- Clone this repository
git clone https://github.com/daf2a/Demo-Laravel-Testing-Feature.git
- Run
composer install
at directory project - Copy
.env.example
to.env
- Run
php artisan migrate
- Run
php artisan key:generate
- Run
php artisan serve
- Make Feature Test and Unit Test
php artisan make:test NoteTest php artisan make:test NoteUnitTest --unit
- Update NoteTest Feature with this code
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use App\Models\Note; use App\Models\User; class NoteTest extends TestCase { use RefreshDatabase; protected $user; protected function setUp(): void { parent::setUp(); $this->user = User::factory()->create(); // var_dump("awal"); } protected function tearDown(): void { parent::tearDown(); unset($this->user); // var_dump("akhir"); } /** * @test * @group test1 */ public function a_note_can_be_created() { // var_dump("create"); $this->withoutExceptionHandling(); $response = $this->actingAs($this->user)->post('/notes', [ 'note' => 'Test Note' ]); $response->assertRedirect('/notes'); $this->assertCount(1, Note::all()); } /** * @test * @group test1 */ public function a_note_can_be_updated() { // var_dump("update"); $this->withoutExceptionHandling(); $this->actingAs($this->user)->post('/notes', [ 'note' => 'Test Note' ]); $note = Note::first(); $response = $this->actingAs($this->user)->put('/notes/' . $note->id, [ 'note' => 'Updated Note' ]); $response->assertRedirect('/notes/' . $note->id); $this->assertEquals('Updated Note', Note::first()->note); } /** * @test * @group test2 */ public function a_note_can_be_deleted() { // var_dump("delete"); $this->withoutExceptionHandling(); $this->actingAs($this->user)->post('/notes', [ 'note' => 'Test Note' ]); $note = Note::first(); $response = $this->actingAs($this->user)->delete('/notes/' . $note->id); $response->assertRedirect('/notes'); $this->assertCount(0, Note::all()); } }
- Update Note Unit Test with this code
<?php namespace Tests\Unit; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use App\Models\Note; class NoteUnitTest extends TestCase { use RefreshDatabase; /** @test */ public function it_can_create_a_note() { $noteData = [ 'note' => 'This is a test note.' ]; $note = Note::create($noteData); $this->assertInstanceOf(Note::class, $note); $this->assertEquals($noteData['note'], $note->note); } /** @test */ public function it_requires_note_field() { // Example Fail // $note = Note::create(['note' => null]); // $this->assertNull($note); // Example Pass $note = Note::create(['note' => 'is not null']); $this->assertNotNull($note); } }
- Run
php artisan test
for testing