17_1_PHPUnit - hpscript/laravel GitHub Wiki

  • ドメインロジックに対してテストを行う
  • vendor/bin/phpunit --filter ${methodName}でテスト実行
  • test用のDBをテスト毎にリフレッシュしてテストしている  -- > use Illuminate\Foundation\Testing\RefreshDatabase;

$ php artisan --version Laravel Framework 6.9.0

$ vendor/bin/phpunit
PHPUnit 8.5.0 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 310 ms, Memory: 16.00 MB

OK (2 tests, 2 assertions)

tests/Feature/ExampleTest.php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}
public function a_new_user_gets_an_email_when_it_register(){
        
    }

未ログインユーザーのリダイレクトテスト

tests/Feature/CustomersTest.php

class CustomersTest extends TestCase
{
    public function only_logged_in_users_can_see_the_customers_list(){
        $response = $this->get('/customers')->assertDedirect('/login');
    }
}

$ vendor/bin/phpunit --filter only_logged_in_users_can_see_the_customers_list

ログインユーザーのリダイレクトテスト

class CustomersTest extends TestCase
{
    use RefreshDatabase;
    
    public function only_logged_in_users_can_see_the_customers_list(){
        $response = $this->get('/customers')->assertDedirect('/login');
    }

    public function authenticated_users_can_see_the_customers_list(){
        $this->actingAs(factory(User::class)->create());

        $response = $this->get('/customers')->assertOk('200');
    }
}

$ vendor/bin/phpunit --filter authenticated_users_can_see_the_customers_list

store methodのテスト

public function a_customer_can_be_added_through_the_form(){

        $this->withoutExceptionHandling();
        $this->actingAs(factory(User::class)->create([
                'email' => '[email protected]'
        ]));

        $response = $this->post('customers', [
                'name' => 'Test User',
                'email' => '[email protected]',
                'active' => 1,
                'company_id' = 1

        ]);

        $this->assertCount(1, Customer::all());
    }

validation test

private function data(){
        return [
                'name' => 'Test User',
                'email' => '[email protected]',
                'active' => 1,
                'company_id' = 1
        ]
    }
public function a_name_is_required(){

        Event::fake();

        $this->actingAs(factory(User::class)->create([
                'email' => '[email protected]'
        ]));

        $response = $this->post('customers', array_merge($this->data(), ['name' => '']));

        $response->assertSessionHasErrors('name');

        $this->assertCount(0, Customer::all());

    }