Unit test Laravel – Test create user – Test validate request

Tram Ho

Write the function create user

To be able to write unit tests, first you need to test, here I need the create user function.

UserController

In the UserController, I wrote the function store to receive the request and use the UserCreateRequest to validate the data, use the userRepository to insert data into the database. Successful function store will return messageSuccess

UserCreateRequest

UserCreateRequest is responsible for validating the input data, refer here

In this we will set the rules for which the messages correspond

UserRepository

UserRepository takes care of processing data and saving to DB.
That’s it, create user section, now let’s start writing tests.

Write unit test create user

The test directory structure will look like this We will create the file UserControllerTest.php in the feature with the command

Now write test for each case only.

  1. Test case update successful

  1. Test the case of false updates when the admin contains login

Because the admin is not logged in, the response returns a 302 error and redirects to login. above part 1 I have used $this->actingAs($admin); to login

  1. Test update data case false because the name field is empty

  1. Test update update data case because the name field is too short

  1. Improperly tested avatar format

The same goes for testing emails or passwords

End

Above are the things I know about unittest, looking forward to receiving suggestions from everyone.

Share the news now

Source : Viblo