Real-world Project to learning about Unit Testing/TDD with Laravel for everybody

Overview

KivaNote - a Laravel TDD Sample Project

codecov

Let me introduce you to KivaNote, a simple real-world application using Laravel to show you how the TDD & Unit Testing works (with PHP & Laravel).

TDD or Unit Testing, it's absolutely good practice and give the developers more confident & trust about their works, their project. Especially importance projects like: Banking, Healthcare, E-commerce,...

I know out there, many people wants to learn how to write unit testing in proper/real-life ways. And the online articles are just:

  • You need to write test
  • Write a func a + b = c then assertEquals(2, plus(1,1))
    • BS, I know right??
  • You need to test this, test that,...
  • blah blah blah,...

Those articles won't help. In fact, you won't probably learn anything from that, especially for newbie. You always need to learn from a real-world project.

So, this little project of mine is going to help you know how to write tests, especially using PHP & Laravel.

Application Introduction

An API Application for a simple note application. It's providing these REST API endpoints

DB Overview

  • 1 User users:
    • n Images images
    • n Notes notes
      • n Note Contents note_contents (history purpose)

Authentication

  • [POST] v1/login
    • Body:
      • email
      • password
    • Response:
      • access_token
  • [POST] v1/logout
    • Header
      • Bearer {authToken}

Note: for all the endpoints below, Bearer {authToken} is required.

Notes

  • [GET] v1/notes: Get notes list of user.
    • Query param:
      • page (default 1)
      • limit (default 10)
  • [GET] v1/notes/{noteUuid}: Get a single note details
  • [POST] v1/notes: Add new note
    • Body
      • title
      • content
  • [PUT] v1/notes/{noteUuid}: Update an existing note
    • Body
      • title
      • content
  • [DELETE] v1/notes/{noteUuid}: Delete an existing note

Images

  • [GET] v1/images: Get images that uploaded by user
    • Query param:
      • page (default 1)
      • limit (default 10)
  • [GET] v/images/{imageUuid}: Get a single image details
  • [POST] v1/images: Upload an image
    • Body (FormData):
      • image (binary)
      • type:
        • self-hosted: save in the filesystem
        • imgbb: save on ImgBB external service
  • [DELETE] v1/images/{imageUuid}: Delete an image

External Services

  • ImgBB: to upload image
    • Also showing you how to write tests for the external APIs

What do we have?

  • PHP8
    • Super recommended, fast and added a lot of cool syntax.
  • Laravel 8
  • PHPUnit (of course)
  • Coverage - using CodeCov (free)

Continuous Integration

Yes. That's where the fun begin. In real life, every projects that have unit testing also have CI process. Some use GitLab CI, some use Jenkins CI.

But for Kiva, I will use GitHub Action.

Test definitions

  • Unit Test
    • Where we're going to test methods of the Class
  • Quick Test
    • Same as Unit, but this test won't involve database, all we need to do is mocking then testing
    • Super fast since no dependencies at all.
  • Feature Test
    • HTTP Test to test the endpoints
  • Integration Test
    • Test multiple endpoints of a flow to see if they are working correctly
      • Not sure we would have it for Kiva, but let's see

Coverage Info

So it depends which kind of projects are you working on to set a coverage goal.

In my opinion, 70%++ would be cool and give me a lot of confident.

When you're writing unit tests, you should coverage all the cases that might happen and that would be totally enough.

Don't do trick or cheat to get high coverage though.

Where should you start?

  • Check out the routes and the Controllers
  • Check out the tests folder
    • Quick first, then Unit and then Feature

Contribute?

Sure, just fork it and add your PR, remember to:

  • Write tests
  • Follow PSR conventions

You like it?

Then please give it a Star

Also, you can support me by donate via Kofi too. Thank you very much!!

Have questions?

Feel free to create an issue or ping me via email. Gracias.

Copyright

By Seth Phat - 2021.

You might also like...
To run time/IO related unit tests (e.g., sleep function calls, database queries, API calls, etc) faster using Swoole.

To run time/IO related unit tests (e.g., sleep function calls, database queries, API calls, etc) faster using Swoole.

PHP Test Generator - A CLI tool which generates unit tests

This project make usages of PHPStan and PHPParser to generate test cases for a given PHP File.

Few additional testing assertions for Laravel views

Laravel View Test Assertions Few additional assertions for testing Laravel views. Why Laravel has well established and documented way of testing reque

A drop in fake logger for testing with the Laravel framework.
A drop in fake logger for testing with the Laravel framework.

Log fake for Laravel A bunch of Laravel facades / services are able to be faked, such as the Dispatcher with Bus::fake(), to help with testing and ass

A video course for laravel artisan to learn creating API using testing

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

A set of helpful assertions when testing Laravel applications.

Installation composer require amirrezam75/laravel-assertions I was working on a project and in order to test oauth2 redirection, I ended up with somet

Full-stack testing PHP framework

Codeception Modern PHP Testing for everyone Codeception is a modern full-stack testing framework for PHP. Inspired by BDD, it provides an absolutely n

AST based PHP Mutation Testing Framework

Infection - Mutation Testing framework Please read documentation here: infection.github.io Twitter: @infection_php Discord: https://discord.gg/ZUmyHTJ

:computer: Parallel testing for PHPUnit

ParaTest The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in y

Owner
(Seth) Phat Tran
Senior Backend Engineer. A Tech-nerd who loves to build awesome stuff every day with a VNmese milk coffee next to him.
(Seth) Phat Tran
SimpleTest is a framework for unit testing, web site testing and mock objects for PHP

SimpleTest SimpleTest is a framework for unit testing, web site testing and mock objects for PHP. Installation Downloads All downloads are stored on G

SimpleTest 147 Jun 20, 2022
Package for unit testing Laravel form request classes

Package for unit testing Laravel form request classes. Why Colin DeCarlo gave a talk on Laracon online 21 about unit testing Laravel form requests cla

null 18 Dec 11, 2022
The modern, simple and intuitive PHP unit testing framework.

atoum PHP version atoum version 5.3 -> 5.6 1.x -> 3.x 7.2 -> 8.x 4.x (current) A simple, modern and intuitive unit testing framework for PHP! Just lik

atoum 1.4k Nov 29, 2022
The PHP Unit Testing framework.

PHPUnit PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. Installat

Sebastian Bergmann 18.8k Jan 4, 2023
PHP unit testing framework with built in mocks and stubs. Runs in the browser, or via the command line.

Enhance PHP A unit testing framework with mocks and stubs. Built for PHP, in PHP! Quick Start: Just add EnhanceTestFramework.php and you are ready to

Enhance PHP 67 Sep 12, 2022
Unit testing tips by examples in PHP

Unit testing tips by examples in PHP Introduction In these times, the benefits of writing unit tests are huge. I think that most of the recently start

Kamil Ruczyński 894 Jan 4, 2023
Learn unit testing with PHPUnit.

PHPUnit Exercise Running PHPUnit ./vendor/bin/phpunit # with filter which tests to run ./vendor/bin/phpunit --filter <pattern> Running Pint ./vendor/

Nopal 2 Aug 23, 2022
API simples utilizando workerman(assincrono) usando TDD, DDD e boas praticas para escalonamento horizontal.

Motivos para usar workerman Além de mais rápido que o swoole, não necessita de libs externas, porém o ponto negativo é não possuir corrotinas, sendo n

Andre 3 Apr 13, 2021
Mock HTTP requests on the server side in your PHP unit tests

HTTP Mock for PHP Mock HTTP requests on the server side in your PHP unit tests. HTTP Mock for PHP mocks the server side of an HTTP request to allow in

InterNations GmbH 386 Dec 27, 2022