Unit test Laravel – Test Repository

Tram Ho

Hello bro. In this article I continue to share some knowledge about writing tests for laravel project. I will show you how to write a repository test in laravel.

1. Preparation

To be able to test the repository, first I need a repository to test, here I will create userRepository and then write tests for it.

  1. First of all, I will create the baseRepository as follows

  1. Next I will create userRepository and rewrite function store to add data instead of using create

Above is creating a repository, if you do not have the knowledge about repository in laravel, you can find it here

2. Write tests for the UserRepository

We will create a UserRepositoryTest file to write the test
Run the command to create unittest:

php artisan make:test Repositories/UserRepositoryTest --unit
The above command will generate a directory with the path test / Unit / Repositories / UserRepositoryTest.php the original file will look like this:

Next write the function testStore to test the function store of the UserRepository

Because I use the User model, UseRepository, uploaderFile, so I will use it

Above there are two functions are testGetModel to test get model and testStore to test store of UserRepository

In the function testStore we will create data and call the store function of the userRepository to add data
$result = $userRepository->store($request);

Then we check to see if the data has been added
$this->assertEquals(1, User::all()->count());
The above statement will return true if the data is successful

it is done . Then we run the command to test:

vendor/bin/phpunit You do the same with the show, update, destroy functions.


Above is the basic knowledge about the Repository laravel test, have any comments please comment in a few posts. Thanks

Share the news now

Source : Viblo