How to create a new Unit test in Laravel to test Relationship

In this very simple tutorial we will cover on how we can create a new unit test in Laravel. As an example of the unit test we will see how we can test relationship existence between two Models.

To get started, assume that you are working on a Blog application and it has common Models like UserPost and Comment.

If you are willing to follow along with this article, you can go ahead an Generate the Model, Controller and Migration File.

As an example Let’s create a unit test to test that Comment belongs to a User.

Generate New Unit Test.

To create a new unit test, go to your terminal and execute the following command.

php artisan make:test CommentTest --unit

Go ahead and add a new test to CommentTest.php which is located in your tests/Unit folder

<?php

namespace Tests\Unit;

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

class CommentTest extends TestCase
{

    use DatabaseMigrations;

    /** @test */    public function it_has_an_owner(){
        $comment = factory('App\Comment')->create();

        $this->assertInstanceOf('App\User', $comment->owner);
    }
}

 

Notice that we are using DatabaseMigrations, that means that we will whip up the database just before starting of the tests and will roll it back once the test is completed.

In the test function it_has_an_owner we are using factory method to create comment in the database and we in the next line we are making sure that $comment->owner is an instance of class 'App\User'.
With this we are asserting the relationship that a comment always belongs to a user.

Go ahead and run this test, by running the following command terminal at your project root directory.

vendor/bin/phpunit tests/Unit/CommentTest.php

If the relationship is not established, this test should fail.

To pass this test, add the following code in your Comment.php Model.

public function owner(){
    return $this->belongsTo('App\User','user_id');
}

That’t all about creating Unit Test in Laravel.

tgugnani: Web Stuff Enthusiast.