Hello friends,
Of all of us, we’ve all Googled how to write Unit Tests, right? But all the online articles, people only show you the theory and the simplest things, like:
- Write a function a + b
- Write a test for that function and assert 1 + 1 = 2
- Write multiple functions
- …
With things like that, how can we know and understand Unit Test well? I need to learn and write Unit Test quickly and clearly.
And the only way is:
- Learn through an existing project, which can be a company project (but not all companies write it)
- Learn through a real life project (this article is mine)
Test concept in Laravel that we will write
- Quick Test
- This test is extended from PHP’s TestCase, we mock everything and test it
- We will write test for each function of the class and cover all the cases
- Unit Test
- This test is extended from Laravel’s TestCase, we can interact with Laravel Database and services
- We will write test for each function of the class and cover all the cases
- Feature Test
- Like Unit, we write Feature test to check if your endpoint (if API) / view (if SSR) is working properly.
- We will check all cases, from authorization check, validation check to controllers, services,…
- Integration Test
- Like Feature, we write complete test for 1 flow (eg register, login, make friends,…), call multiple endpoints at the same time.
Learning sequence
- Check routes
- Go to the Controllers
- See the FormRequests for auth + validation rules
- View the Services used in Controllers
- And finally, reading the tests, you will know what you have to test
My Repositories (IRL Projects) that you can refer to
- Kiva: https://github.com/sethsandaru/kiva-laravel-tdd – an API project with endpoints for creating notes
- EloquentDocs: https://github.com/sethsandaru/eloquent-docs – helper command to generate phpDoc for your Eloquent Models (IDE friendly, like PHPStorm)
- SaaS Ready: https://github.com/shipsaas/ready – Ready packs a dozen basic entities to help you bootstrap your startup project as quickly as possible.
The projects above all have coverage > 80%, test quite a lot.
(Also you can also learn more about CI and its settings = Github Actions, check the .github directory)
(There are a few more projects, will share more later)
Thank you and good luck with your studies!