Write unit tests, save time & lifes

Write unit tests, save time & lifes

Dec 9, 2022

2 min read

Hey guys,

Unit testing or TDD (Test-driven development) is a thing for years, IKR?

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 fail, 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 user's age below 18

  • When user's age above or equal 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 & confident when releasing features.

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

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

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

Cons

  • Yes yes I know, it takes time.

Conclusion

Even 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 much reliable tests as you can

  • Oursourcing:

    • Integraiton test to test a whole flow. Would come in handy for refactoring or upgrading softwares.

Cheers!