Laravel ile projenize nasıl testler yazacağınıza bakalım. Test şu komutla oluşturulur.
php artisan make:test BasicTest // veya php artisan make:test PostTest --unit
Test işlemlerini denem bir veritabanında yapacağımız için db oluşturmalısınız. Daha sonra anadizindeki phpunit.xml dosyasını düzenleyin.
<server name="DB_CONNECTION" value="mysql_testing"/>
Sqlite vb. de kullanabilirsiniz.
test/Feature/BasicTest.php dosyasını açın. Şu şekilde bir sınıf ve metod oluşacaktır.
<?php # test/Feature/BasicTest.php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class BasicTest extends TestCase { public function testExample() { $response = $this->get('/'); $response->assertStatus(200); } }
Test kontrolü için 2 yöntem vardır;
./vendor/bin/phpunit // daha iyi kontrol için laravelin sunduğu komut tercih edilmeli. php artisan test
Gelelim örnek test metoduna. Hemen bir içerik ekleyip bu içeriğin veritabanına eklenip eklenmediğni test edelim.
<?php public function test_can_create_post() { $this->withoutExceptionHandling(); // Hataları detaylı görmek için kullanılır. $response = $this->post('posts', ['title' => 'Sally2', 'description' => 'hoop sda sd ads']); $this->assertCount(1, Post::all()); }
Factory kullanarak da fake veri oluşturup Test işleminde kullanabilirsiniz.
<?php $user = Post::factory()->make(); // sadece oluşturur $user = Post::factory()->create(); // oluşturup db'ye kaydeder $this->assertDatabaseCount('posts', 1);
Örnek Api Test metodu;
<?php public function test_can_create_post() { $data = [ 'title' => $this->faker->sentence, 'content' => $this->faker->paragraph ]; $this->post(route('posts.store'), $data) ->assertStatus(201) ->assertJson($data); }
Kullanılabilir örnek metodlar;
<?php assertCookie assertCookieExpired assertCookieNotExpired assertCookieMissing assertCreated assertDontSee assertDontSeeText assertExactJson assertForbidden assertHeader assertHeaderMissing assertJson assertJsonCount assertJsonFragment assertJsonMissing assertJsonMissingExact assertJsonMissingValidationErrors assertJsonPath assertJsonStructure assertJsonValidationErrors assertLocation assertNoContent assertNotFound assertOk assertPlainCookie assertRedirect assertSee assertSeeInOrder assertSeeText assertSeeTextInOrder assertSessionHas assertSessionHasInput assertSessionHasAll assertSessionHasErrors assertSessionHasErrorsIn assertSessionHasNoErrors assertSessionDoesntHaveErrors assertSessionMissing assertStatus assertSuccessful assertUnauthorized assertViewHas assertViewHasAll assertViewIs assertViewMissing $this->assertDatabaseCount('users', 5); $this->assertDatabaseHas('users', [ 'email' => 'sally@example.com', ]); $this->assertDatabaseMissing('users', [ 'email' => 'sally@example.com', ]); use App\Models\User; $user = User::find(1); $user->delete(); $this->assertDeleted($user); $this->assertSoftDeleted($user);
İlk Yorumu Siz Yapın