30 Days of Automated Testing:Using PHPUnit【D03】

Beginner: First Test

WilliamP
3 min readJan 8, 2023

In the previous article, we set up the environment, and today we will write our first unit test!

But before we do that, let’s first understand the “3As” of unit testing.

The 3As of Unit Testing

The “3As” refer to the following three English words:

  • Arrange: Initialize, such as preparing mock data
  • Act: Perform the test object
  • Assert: Verify the result

A good unit test case should contain the above structure, performing Arrange → Act → Assert in order and showing the verification result. This is a complete unit test program.

First Test

Now is the time to write the test!

Before we start writing our first test, let’s create a test object. We’ll use a BMI calculation function as an example!

In the app\Services folder, create TestService.php:

<?php

namespace App\Services;

class TestService
{
public function calculateBmi(float $height, float $weight): float
{
if ($weight <= 0) {
return 0.0;
}

return $weight / ($height * $height);
}
}

Then let’s create the test immediately. In the workspace container, in the project folder, execute the following command to create the unit test:

php artisan make:test TestServiceTest --unit

After creating TestServiceTest.php, let’s write the test function:

<?php

namespace Tests\Unit;

use App\Services\TestService;
use PHPUnit\Framework\TestCase;

class TestServiceTest extends TestCase
{
/**
* Test calculateBmi
*/
public function testCalculateBmi()
{
// Arrange
$service = app(TestService::class);
$height = 1.6;
$weight = 64.0;

// Act
$actualBmi = $service->calculateBmi($height, $weight);

// Assert
$expectedBmi = 25;
$this->assertEquals($actualBmi, $expectedBmi);
}
}

First, let’s explain the logic of each block of code:

// Arrange
$service = app(TestService::class);
$height = 1.6;
$weight = 64.0;

Here, we first create an instance of TestService, $service, and initialize the data needed to execute the test object later.

// Act
$actualBmi = $service->calculateBmi($height, $weight);

This is the block of code to be tested.

// Assert
$expectedBmi = 25;
$this->assertEquals($actualBmi, $expectedBmi);

Verification is performed, where $this->assertEquals is the first Assert function we are currently using. It verifies whether the first input value (actual value) is equal to the second input value (expected value).

After the test object and test case are ready, let’s execute the test:

./vendor/bin/phpunit

You should see the following output result:

Congratulations on completing the first unit test! Wasn’t it easy?

Next we will introduce commonly used Assert functions.

If you liked this article or found it helpful, feel free to give it some claps and follow the author!

Reference:

Articles of This Series

--

--