Let’s Have Fun Testing with PHPUnit and Carbon Package!

Shaon Majumder
4 min readFeb 9, 2024

--

Hey there, fellow code adventurers! Welcome to this exciting journey into the world of testing with PHPUnit and the awesome Carbon package. 🚀

Prerequisites: Gear Up!

Before we embark on this thrilling quest, make sure you’ve got your development gear ready:

  • Composer: Your trusty sidekick for managing PHP dependencies.
  • Laravel Framework: Our trusty steed for building powerful web applications.

Step 1: Prepare Your Weapons

To start, let’s set up our Laravel project by creating a new directory and installing Laravel using Composer. Open your terminal and execute the following commands:

composer create-project laravel/laravel phpunittest
cd phpunittest

If you follow along with my code. Then you can clone my repository :

git clone https://github.com/ShaonMajumder/phpunittest.git
cd phpunittest

Step 2: Install PHPUnit — Our Testing Battle Armor

First things first, let’s gear up with PHPUnit, the ultimate testing battle armor for PHP. Open your terminal and execute the following command:

composer require phpunit/phpunit

PHPUnit is now ready to help us slay bugs and conquer code!

Step 3: Install Carbon Package — The Date & Time Master

Next, let’s equip ourselves with the Carbon package, our reliable guide to navigating the coding wilderness. In your terminal, execute this command:

composer require nesbot/carbon

With Carbon by our side, we’ll master the intricacies of date and time manipulation.

Step 4: Create Carbon Package Test File — Forge Your Testing Arsenal

Time to forge our testing arsenal! With Laravel’s Artisan command, creating a test file is as easy as summoning a spell. Execute this magical command in your terminal:

php artisan make:test CarbonPackageTest

Behold! The CarbonPackageTest.php file has materialized in our tests/Feature directory, ready for battle.

Step 5: Unleash Your Tests — Let the Adventure Begin!

With our arsenal prepared, it’s time to unleash our tests upon the code realm! Open the CarbonPackageTest.php file and let your testing prowess shine. Here's a glimpse of what your tests might look like:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use Illuminate\Support\Facades\Log;

use Carbon\Carbon;

class CarbonPackageTest extends TestCase
{

protected function setUp(): void
{
parent::setUp();
// Any necessary setup can be done here
}

public function testToday()
{
$today = Carbon::today();
$this->assertInstanceOf(Carbon::class, $today);
}

public function testAddDays()
{
$date = Carbon::parse('2024-02-09');
$newDate = $date->addDays(7);
$this->assertEquals('2024-02-16', $newDate->format('Y-m-d'));
}

public function testBasicAssertions()
{
$this->assertTrue(true);
$this->assertFalse(false);
$this->assertNull(null);
$this->assertNotNull(123);
$this->assertIsArray([]);
$this->assertIsBool(true);
$this->assertIsFloat(3.14);
$this->assertIsInt(42);
$this->assertIsNumeric('123');
$this->assertIsObject(new \stdClass());
$this->assertIsString('hello');
$this->assertIsScalar('123');
$this->assertIsCallable('strlen');
$this->assertIsIterable([]);
$this->assertIsNotArray(false);
$this->assertIsNotBool('');
$this->assertIsNotFloat('hello');
$this->assertIsNotInt('123');
$this->assertIsNotNumeric(false);
$this->assertIsNotObject('string');
$this->assertIsNotString(123);
$this->assertIsNotScalar([]);
$this->assertIsNotCallable(null);
$this->assertIsNotIterable(null);
$this->assertInstanceOf(Carbon::class, Carbon::now());
}

public function testArrayAssertions()
{
$array = ['apple', 'banana', 'cherry'];

$this->assertContains('banana', $array);
$this->assertNotContains('grape', $array);
$this->assertCount(3, $array);
$this->assertEmpty([]);
$this->assertNotEmpty($array);
}

public function testEqualityAssertions()
{
$this->assertEquals(10, 5 + 5);
$this->assertNotEquals(10, 6 + 5);
$this->assertSame('5', '5');
$this->assertNotSame('5', 5);
}

public function testStringAssertions()
{
$string = 'Hello, world!';

$this->assertStringContainsString('world', $string);
$this->assertStringNotContainsString('moon', $string);
$this->assertMatchesRegularExpression('/\w+,\s\w+!/', $string);
$this->assertDoesNotMatchRegularExpression('/\d/', $string);
$this->assertStringStartsWith('Hello', $string);
$this->assertStringStartsNotWith('Hola', $string);
$this->assertStringEndsWith('!', $string);
$this->assertStringEndsNotWith('?', $string);
}

public function testComparisonAssertions()
{
$this->assertGreaterThan(5, 10);
$this->assertGreaterThanOrEqual(10, 10);
$this->assertLessThan(10, 5);
$this->assertLessThanOrEqual(5, 5);
}

public function testFileAssertions()
{
$this->assertFileExists(__FILE__);
$this->assertFileDoesNotExist('public/index2.php');
$this->assertFileIsReadable(__FILE__);
$this->assertFileIsNotReadable('public/index3.php');
$this->assertFileIsWritable(__FILE__);
$this->assertFileIsNotWritable('public/index3.php');
}

public function testDirectoryAssertions()
{
$this->assertDirectoryExists(__DIR__);
$this->assertDirectoryDoesNotExist('public2/');
$this->assertDirectoryIsReadable(__DIR__);
$this->assertDirectoryIsNotReadable('public3/');
$this->assertDirectoryIsWritable(__DIR__);
$this->assertDirectoryIsNotWritable('public3/');
}

public function testExceptionAssertions()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('This is an invalid argument.');
$this->expectExceptionCode(100);

throw new \InvalidArgumentException('This is an invalid argument.', 100);
}

public function testMiscellaneousAssertions()
{
$this->expectNotToPerformAssertions();
$this->markTestIncomplete('This test is not yet implemented.');
$this->markTestSkipped('This test is skipped for a reason.');
}
}

Step 5: Preparing Files for Testing

Before running the tests, it’s essential to prepare the necessary files to ensure the tests run smoothly. Follow these steps to set up the required files:

# Create a directory for testing
mkdir -p testdirectory
mkdir -p testdirectory3

# Create a PHP file within the testing directory
touch testdirectory/test3.php

# Adjust permissions for testing directory and file
chmod -r testdirectory3 # Remove read permissions from testdirectory3
chmod -w testdirectory3 # Remove write permissions from testdirectory3
chmod -r testdirectory/test3.php # Remove read permissions from test3.php
chmod -w testdirectory/test3.php # Remove write permissions from test3.php

These commands will create a testing directory (testdirectory) and a PHP file (test3.php) within it. Additionally, permissions are adjusted on testdirectory3 and test3.php to simulate different scenarios for testing.

Now, you’re ready to run your tests with the prepared files. Prepare your weapons, fellow adventurers! It’s time to face the trials and tribulations of testing.

Step 6: Run PHPUnit Tests — The Moment of Truth!

With our tests written, it’s time to face the final challenge! Navigate to the root of your Laravel project and execute the following command:

php artisan test

Result :

As the test results unfold before your eyes, rejoice in the victory of bug-free code and the assurance of quality!

And there you have it, fellow adventurers! With PHPUnit and the Carbon package by your side, you’re ready to conquer the code wilderness and build remarkable software.

Happy testing, and may the bugs be ever in your favor! 🐛✨

--

--

Shaon Majumder
Shaon Majumder

Written by Shaon Majumder

Software Engineer | Author | Data Scientist

No responses yet