PHP is a powerful server side language. It is well know and have domination from years. In Coding level PHP supports many advanced features. Today we are going to discuss about PHP Unit testing. For test driven development understanding with php Unit Testing is a Must.
In Computer programming languages unit testing is a software testing method, Set of one or more program modules with associated control data are tested to determine whether they are fit for use.
We are going to see example in PHP Language. Using PHP Unit Testing package.
To install php unit in any project we can use composer. If you do not know how to install composer try these links:
Installation is quite simple we need to run below given composer command
composer require phpunit/phpunit
Once installation complete, Then we can proceed but if in case you want to install using Documentation then check Official Documentation
We need to create "tests" folder in project. and inside it we can have sub folders such as feature or unit. So in our case we are doing unit testing so we must have unit folder inside tests folder.
Here in this tests/unit directory we will add test classes but before that we need to setup configuration for testing.
So after installing "phpunit" from above given composer command, We can now run tests using command "./vendor/bin/phpunit".
Composer command will add a vendor directory in project folder.
If we run "./vendor/bin/phpunit" we can see configuration options available by php-unit package.
But we are going
But we are going to setup a phpunit.xml file for default configuration. So we do not have to add these options such as "--bootstrap" in command "./vendor/bin/phpunit".
SO in root of project we create "php unit.xml".
which looks like this
Here we are setting bootstrap which means this file will run before every test. And we are using file to run "vendor/autoload.php".
Another main thing is we are setting test directory as "tests".
so when we are going to run command this file will look in tests directory.
Now lets create a "SampleTest".
So as we have directory setup as "tests/unit" there we add our first sample test. It should be a Class which will look something like this
Here we have Sample class which has a test defined. Notice test function requires name starting with keyword "test".
Now this test "assertTrue" that means if we pass true in assert then this test will pass. if we pass false in assertTrue then it will fail the test.
So basically we can add our code which we want to test in function before assert statement. And if it returns true we can pass the value to
"$this->assertTrue".
So bottom line is if we expect true coming from our code and we pass true to assert statement we get passed test.
Check our Video guide for more clarity.