rtCamp notes, day 69 of undefined

PHP Unit Testing

What is unit testing?
A: Unit testing ensures that whatever code we have written is working as expected, this saves time for the developer to manually test the code again and again, instead of it we can just write test cases where we can define the expected outcome and compare it against the outcome our code is producing.

Creating a PHPUnit Test

Tests can be created by extending the use PHPUnit\Framework\TestCase class.

The command to run the test cases ->

./vendor/bin/phpunit tests

This would run all the tests found inside the tests directory.
How does it know that which file is a test file?
A: Every file appended with Test.php would be considered as a test file. For example AryanTest.php, MovieLibraryTest.php etc etc

Now inside the Test file as well, we need to create functions which define the tests, now how would it know which function is a test function and which is just a basic function? There are two ways of doing that.
We can either add the Annotation for the test [ annotations are @author @param those tags inside the comments ], the annotations for the test would be @test and our code would look like

<?php
use PHPUnit\Framework\TestCase;

class AryanTest extends TestCase {

	/** @test */
	public function aryan_working_properly() {

	}

}

Another way we can specify it is a test is by prepending the function name with test, for example

<?php
use PHPUnit\Framework\TestCase;

class AryanTest extends TestCase {

	public function test_aryan_working_properly() {

	}

}

Both of these would be considered as the tests.

Now defining the content inside the test,

<?php
use PHPUnit\Framework\TestCase;

class AryanTest extends TestCase {

	public function test_aryan_working_properly() {
		$expected = 5;
		$result   = $this->get_aryan_result( 3, 2 );
		$this->assertSame( $expected, $result );
	}

	public function get_aryan_result( $a, $b ) {
		return $a + $b;
	}

}

This assertSame would check if the expected and the result value is same and would pass or fail the test case on the basis of that.
We can use this to check the returned value from our functions and can check if they are working properly.

Leave a Reply

Your email address will not be published. Required fields are marked *