20 Jul 2019 . Php . 1.6K views
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.
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-
test
. So if you write any code that doesn't have prefix called test, PHP Unit won't test that. /** @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.
Laravel PHP artisan Route List command
How to add new columns to the existing table in Laravel migration
An Introduction to Laravel Policy
The Standard Approach to Validate Laravel Form Request
Building a delighted RESTful API with Laravel
Apply The Open Closed Principle in Laravel | Part 1
Laravel delete files from Public Folder
Apply The Open Closed Principle in Laravel | Part 2
Deep Diving into Laravel Subquery