Unit Testing in PHP with PHPunit

in utopian-io •  7 years ago  (edited)

Screenshot_21.png

We will learn about unit test. in this tutorial I will use https://phpunit.de/. Php unit is a very popular framework testing. well in some other programming languages. there are also other unit tests. the usefulness of this framework is not a framework for building websites like laravel or codeigneter. but the framework is for testing, so we can test our code automatically. when we test a small unit or one small function of our website. for more details , lets start the tutorial.

What Will I Learn?

  • Setting Unit test
  • Using PSR-4 Autoload
  • Make unit testing to test the functions

Requirements

  • Install Php unit
  • Localhost (xampp,wampp or etc)
  • Intermediate PHP OOP
  • Composer

Difficulty

  • Advanced

Install Php Unit and Settings

The first step , We must to install the dependency of phpunit first, to install it. I use the composer. My php version is php version 5.6, So I use version 5 on php unit. if version of php> = 7. You should use php unit 6 .

composer require --dev phpunit/phpunit ^5

Screenshot_16.png

  • Add configuration file
  • I will make the configuration file , So we can use it automatically and not call it one by one. Its configuration file is in the form .xml .
    <phpunit
        bootstrap="vendor/autoload.php"
        colors="true"
        stopOnFailure="true">
        <testsuites>
            <testsuite name="testsuite">
                <directory>Test</directory>
            </testsuite>
        </testsuites>
    </phpunit>
    

    bootstrap="vendor/autoload.php" : Files that we need to load before we run its test.

    colors="true" : We give the color in terminal to be seen more clearly if an error occurs . The value is boolean(true or false).

    stopOnFailure="true": To stop the code in case of error. The value is boolean(true or false).

    < testsuites >< /testsuites > : Keep in mind the < testsuites >tag, under < phpunit >tag, and the < testsuites > tag , add < testsuite > tag .

  • Make Structure Folder
  • Now we have to set the folder structure . I have created 2 new folder app folder and test.

    Screenshot_19.png

    app Folder : In this folder we will put the projects

    testFolder : In this folder we will make our code testing.

  • Make PSR-4 autoload
  • We will use the classes to in use outside the folder, now to facilitate us and so we can use the system namespace, we need psr-4 autoload.
    
    {
        "require": {
            "phpunit/phpunit": "5"
        },
        "autoload":{
            "psr-4":{
                "App\\": "app"
            }
        }
    }
    
    

    "App\": "app" : "App\" is the namespace system we will use. and "app" is the name of the folder that we will load. Well after we specify its autoload system, we must update composer.json, in this way :
    composer dump-autoload -o

    Create Testing Unit

    There is an interesting in unit testing system, usually when we want to test something we first create a function then we testing the function. but most programmers advise you to create unit testing first. It's ounds a little weird but there is a reason that will why we make unit testing, The first if we make a function or a project that is large of course we will be lazy to make its unit testing. The second We have a purpose about the function of coding that we will make.

  • Create testing file
  • I will create a testing file that is testingUser.php.
    
    <?php
    use PHPunit\Framework\TestCase;
    use App\models\Users;
    class testingUser extends TestCase
    {
        /** @test */
        public function checkUserFirstname(){
            $user = new Users;
            $user->setFirstName('Utopian');
            $this->assertEquals($user->getFirstName(),'Utopian');
            $user->getFirstName();
        }
    }
    
    
    use PHPunit\Framework\TestCase; : Use dependency of PHPunit.

    use App\models\Users; : Use the user class in the app folder.

    class testingUser extends TestCase : We extends the existing classes in the PHP dependency unit TestCase.
    $user->setFirstName('Utopian'); : This is a function that I will test, well the function will be created in model->user.

    $this->assertEquals($user->getFirstName(),'Utopian'); : We can compare by using $user->getFirstName(), when we get first name we will compare with ''utopian ''.
    $user->getFirstName(); : This function to get getFirstName.

  • Create function to Testing
  • And now we will create a function that we will test with the file testing we have created above. I created a file for testing in the app->models folder.

    Screenshot_20.png

    Users.php

    
    <?php
    namespace App\models;
    class Users 
    {
        public $firstName;
        public function setFirstname($firstName){
            $this->firstName = $firstName;
        }
        public function getFirstname(){
            return $this->firstName;
        }
    }
    
    
    namespace App\models; : The namespace system we created using psr-4.

    public $firstName; : for property declarations, the name is $firstName

    setFirstname($firstName){}: This function to set its username, the setFirstname must be same with then function name in testingUser.php.

    $this->firstName = $firstName; : To assign property value, we give its property firstName name and its value is taken from $ firstName.

    function getFirstname(){} : This function to get firstname to get the name we have created in unit test before, Its with 'utopian' name.

    return $this->firstName; : We can return the firstName , So We can get the name .

    And we can try to check if our unit testing is running well, you can open your project and run a command prompt and type phpunit. If there is no error you can see the testing run properly.

    Screenshot_21.png

    And in the end we have created a unit test to see if the function that we run is working as it should. It is a bit confusing when we have to make unit tests first , before we make our function. But it will benefit a lot if we use the system. Thank you for following my tutorial. hopefully this tutorial useful for you.



    Posted on Utopian.io - Rewarding Open Source Contributors

    Authors get paid when people like you upvote their post.
    If you enjoyed what you read here, create your account today and start earning FREE STEEM!
    Sort Order:  

    You do things when the opportunities come along. I've had periods in my life when I've had a bundle of ideas come along, and I've had long dry spells. If I get an idea next week, I'll do something. If not, I won't do a damn thing.

    Semangat Brur....!!!

    Itu3 org d atas bot apa nyampah ya

    Phising itu ngincar akunmu hati2...

    Your contribution cannot be approved because it is a duplicate. It is very similar to a contribution that was already reviewed here.

    Related Rules:

    • Duplicate submissions (by the same or different user) will be automatically rejected.
    • Content shared previously will be rejected if a moderator discovers plagiarism, and the user submitting it will be banned from Utopian.

    You can contact us on Discord.
    [utopian-moderator]