Writing your first PHP Unit Test | Learning PHPUnit - Part 2

Writing your first PHP Unit Test | Learning PHPUnit - Part 2

Posted on:July 21, 2019 at 10:00 AM

Hello

Today, I am going to show you writing your first PHP Unit Test. Keep it in your mind that, this series is for absolute beginner those don’t use testing in their code. Let’s start.

Prerequisites

Create your first PHP Unit Test

Create a new folder called unit inside your tests directory. Then create a new class called FirstTest.php. Then create an empty class like this-

FirstTest.php

<?php

class FirstTest extends \PHPUnit\Framework\TestCase {
	// Your code should be here
}

Please make sure that your class has extended from \PHPUnit\Framework\TestCase. Now, in your terminal, run vendor/bin/phpunit. If you can’t see any error, that means it works fine. Let’s write your first test then.

In your FirstTest file, add a method like this-

	public function test_my_first_test()
	{
		$this->assertTrue(true);
	}

Here take a note few things-

  • I use a prefix called test. So if you write any code that doesn’t have prefix called test, PHP Unit won’t test that.
  • Another way to make a function testable is to make a comment on method like the following way. In that way, you can skip the prefix.
	/** @test */
	public function my_first_test()
	{
		$this->assertTrue(true);
	}

Remember that, without using any of these points, PHP Unit won’t consider your method to test.

So, the whole file looks like that-

<?php

class FirstTest extends \PHPUnit\Framework\TestCase {

	public function test_my_first_test()
	{
		$this->assertTrue(true);
	}
}

Now, run vendor/bin/phpunit in your terminal and you should able to a passed test result, that is in the green color, right?

Cool, you have successfully written your first test on PHP Unit. Although this test is for just checking assertTrue() with a true value. This should return a passed test result all the time.

So, in the following post, I will try to write more details about testing.

Thank you.