CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Development PHPUnit Tutorial For Beginners

PHPUnit Tutorial For Beginners

Rana Ahsan July 23, 2014 4 Comments


 PHPUnit Tutorial For Beginners    

I am using PHPUnit for quite sometime now. Though was thinking few times to write about it, but it didn’t happen till now. In fact, this is my first tutorial on testing as well. The official documentation/getting started guide is already quite good for starting. However, I personally find it a little insufficient in several cases and could be little hard to start with as a beginner. Thus, I am writing this PHPUnit tutorial to explain it as easily possible with my preferred/recommended way to start using PHPUnit. Also, though this is a beginners level tutorial on phpunit, I assume you know/have sound concept about what unit testing is!

Alternative To PHPUnit:

There is another simpletest for PHP, which you can checkout as well if you want. However, though I haven’t practically used it yet, but seems it doesn’t have as much support/flexibility as PHPUnit. Also, even being PHPUnit unofficial, still it’s almost being used everywhere, so sticking with it is a good idea, I guess.

Installing PHPUnit:

It is possible to get PHPUnit installed for per project basis or system wide as well. I personally prefer per project basis most. Lets installed this way using composer:

{
	"require": {
                "phpunit/phpunit": "dev-master"
	}
}

Even if you are not using composer for you project, you can have it there without affecting anything else and use its CLI comfortably. In case you are not familiar with composer, get it installed easily on your system, copy the above JSON to a file named ‘composer.json’ on your project directory and run ‘composer update’ command. And you should be done.

Now, to verify the installation, use your terminal/command line tool and go to your project directory. Then run the following command:

$./vendor/bin/phpunit
PHPUnit 4.1.3 by Sebastian Bergmann.

Usage: phpunit [options] UnitTest [UnitTest.php]
       phpunit [options] <directory>

Code Coverage Options:
..............

If all OK, you should get some output as like above.

Initial PHPUnit Configuration:

Well, it’s not mandatory to maintain a configuration file. You can run specific PHPUnit class/method right from your CLI . However, I like, prefer and will strongly recommend to have a configuration file with all details so that you can just run “phpunit” command and it itself take care of the rest.

Yes, if there is a configuration file named ‘phpunit.xml’, it’s automatically read by the library and act accordingly. A sample configuration file is as below:

<?xml version="1.0" encoding="UTF-8"?>

<phpunit bootstrap="./tests/bootstrap.php"
        convertWarningsToExceptions="true"
        convertNoticesToExceptions="true"
        convertErrorsToExceptions="true"
        backupStaticAttributes="false"
        processIsolation="false"
        stopOnFailure="false"
        backupGlobals="false"
        syntaxCheck="false"
        colors="true">
    <testsuites>
        <testsuite name="HelloWorld Test Suite">
            <directory>./tests/</directory>
            <file>./path/to/file.php</file>
        </testsuite>
    </testsuites>
    <php>
        <var name="SOME_CONSTANT_CONFIG" value="Test Value" />
    </php>
</phpunit>

Above is a very simple XML configuration. As you can see, you can specify directories where your test files are. You can specify individual files as well. Also, here you can categorize tests into separate test suit as well. Then you can just run one specific suit from CLI.

PHPUnit HelloWorld Test Case:

Lets create a test to try out. It’s good to have tests on a separate dedicated directory, usually named as ‘tests’. Create a single php file named ‘HelloWorldTest’ and put below content in it:

class HelloWorldTest extends \PHPUnit_Framework_TestCase
{
    function testHelloWorld()
    {
        $this->assertTrue(true);
    }
}

Just to tell you one thing here, remember, a phpunit test method name always start with ‘test’ and then rest of the name goes one. Any method that doesn’t start with ‘test’ will be ignored by phpunit.

For this first test, remove the bootstrap option from XML configuration(as we don’t have any now). And run the following command:

$./vendor/bin/phpunit

If all are OK, you should see something like as below:

PHPUnit 4.3-g39989b7 by Sebastian Bergmann.

Configuration read from /path/to/phpunit.xml

.

Time: 793 ms, Memory: 2.50Mb

OK (1 test, 1 assertion)

As you can see, in summary output, it shows the most necessary information in brief like, how many tests(each test method is considered as single test, however a single test can include as many assertion as you need) ran. how much time/memory it took etc.

Understanding Assertion:

Assertion is the process of verifying an expected output to an actual output. This is something like this – you will provide set of input(s) to a unit of functionality(usually a specific method) in your application. Then you verify whether your desired output is same as the actual output the method returning to you. If yes, it passes the test, otherwise it fells.

There are several built-in assert* methods(which are standards on unit tests of other programming language as well) that you will be using to compare value your application is returning to the value you are expecting. Lets say, your application has a class that checks whether a user is logged in or not. This could be written in PHPUnit as below:

function testAuthorized()
    {     
        $this->assertTrue(Auth::isLoggedIn());
    }

In similar way you can compare two values as well:

function testPHPUnitMethod()
    {
        $company = CompanyModel::getByName("companyName");        
        $this->assertEqual(50, $company->noOfEmployee());
    }

There are lots of other assertions available which you can use to compare almost anything you might need.

Initialization/Destruction:

Well, it might happen that, you have several test cases that need to do several common steps at the beginning. To make a common generalization of such situations, phpunit comes up with built-in support for ‘setUp’ and ‘tearDown’ method, which you can write
to do common initialization and destruction mechanisms. Example shown below:

    public function setUp()
    {
        $this->db->ClearDatabase();
        $this->session->start();
    }
    
    public function tearDown()
    {
        $this->session->destroy();
    }

Final Words:

As a getting started point, hopefully this small PHPUnit tutorial should be enough, I guess. However, if you are not clear about anything or if you think some other information will be helpful to add, please let me know via comment and I will try to add them soon. Also, I am willing to write more on this later on. Happy coding 🙂

Related

Filed Under: Development Tagged With: php, phpunit, unit-test

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. Nishant says

    November 17, 2015 at 3:09 am

    Without class ,How to test PHP functions?

    I have following simple code inside my Index.php file

    So how to test only message() functin without class by using PHPUnit inside NetBeans Framework.

    Reply
    • swapnil says

      March 22, 2016 at 4:49 am

      This will help you
      http://stackoverflow.com/questions/36016250/is-it-possible-to-unit-test-php-files-other-than-class-file-using-phpunit/36016329#36016329

      Reply
  2. Abdul Baasit Ismail says

    July 8, 2016 at 3:49 am

    $this->assertEqual(50, $company->noOfEmployee());
    this should be ‘assertEquals’

    but further than that, everything worked thanks!

    Reply
  3. Muhammad Azaz Qadir (@azazqadir) says

    March 15, 2017 at 8:28 am

    Nice guide but I think you forgot to mention that before starting the test process, a proper directory structure for the files to be tested is required (mentioned here: https://www.cloudways.com/blog/getting-started-with-unit-testing-php/ ). This way you can efficiently run the test of your code.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • How To Work With CodeIgniter Pagination
  • Get Facebook C# Api Access Token
  • Getting Started With HTML5 Web Speech API
  • How To Work With Codeigniter Caching In PHP
  • How To Work With Multithreaded Programming In C#.NET Application

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in