Laravel Testing - How to do Login PHP UnitTest

Laravel Testing - How to do Login PHP UnitTest

Posted on:July 23, 2019 at 10:00 AM

Today, I will show you how to do Login PHP UnitTest with Laravel. This article will cover the login testing part only.

I assume that you have migrated laravel default database and create the respective model for that.

Create User Factory

Firstly, let’s create a user factory for login. You need to run the following command to create a user factory.

php artisan make:factory UserFactory

It will create a file called UserFactory in database > factories folder. Now let’s update the factory file like this-

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt('password')
    ];
});

Now, let’s create a LoginTest file. To create a LoginTest file, you need to run the following command in the terminal.

php artsian make:test LoginTest

It will make file called LoginTest in the tests/Feature folder. Now let’s create a method there.

/** @test */
public function a_visitor_can_able_to_login()
    {
        $user = factory('App\User')->create();

        $hasUser = $user ? true : false;

        $this->assertTrue($hasUser);

        $response = $this->actingAs($user)->get('/home');

        $response->assertStatus(200);
    }

The whole file will be like this-

<?php

namespace Tests\Feature;

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

class LoginTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function a_visitor_can_able_to_login()
    {
        $user = factory('App\User')->create();

        $hasUser = $user ? true : false;

        $this->assertTrue($hasUser);

        $response = $this->actingAs($user)->get('/home');
    }
}

So far we have done writing our test. Now let’s run testing. In the terminal, run this-

vendor/bin/phpunit

Now you should able to see the result of your testing either pass or fail.

Thank you.