Write unit tests, save time & lifes

Write unit tests, save time & lifes

2 min read

Hey guys,

Unit testing or TDD (Test-driven development) has been a thing for years, hasn't it?

I'll quickly talk about this and share with you guys the experience.

TDD

The practice of TDD is:

  • You write test

  • You write code

  • You run test, test fails, you update the code until the test is passed

But honestly, in real life, we write the code first then write the test 不. It is acceptable as well.

Unit Testing

You write a method/function, you write test for that function. That's basically how unit testing works.

Sample method:

function createUser(string $fullName, int $age): User
{
    if ($age < 18) {
        throw new DomainException('User must be an Adult');
    }

    return User::create(['name' => $fullName, 'age' => $age]);
}

To write good and reliable test cases, you would need to cover all the cases:

  • When the user's age is below 18

  • When the user's age is above or equal to 18

  • Data must be created successfully

Example:

public function testCreateUserFailsDueToAgeBelow18()
{
    $this->expectException(DomainException::class);
    createUser('Seth Phat', 15);
}

public function testCreateUserSuccessfully()
{
    $user = createUser('Seth Phat', 18);

    $this->assertNotNull($user);
    $this->assertDatabaseHas('users', [
        'name' => 'Seth Phat',
        'age' => 18,
    ]);
}

Easy, right?

Write as many functions as possible. A minimal function would be super easy to write test.

Pros of having unit testing

  • More trust & confidence when releasing features.

  • Refactoring would be fun and not scary at all, tests got your back.

    • When you refactor things and the test fails => you know something went wrong in the development phase.
  • Same as refactoring: upgrading the framework, library, or language's version. You can list out the out-of-date/breaking changes and take needful actions from them.

    • Imagine upgrading the framework without tests, especially for major versions (eg Laravel 8.x to 9.x), it would cost a lot of time (and money) to do the regression test.

Cons

  • Yes yes I know, it takes time.

Conclusion

Even if your project is a big product or an outsourcing one. Let's always write tests.

  • Product:

    • Cover things as much as you can

    • Provide as many reliable tests as you can

  • Outsourcing:

    • Integration test to test a big flow.

    • or E2E test, to test the important features.

Cheers!