Back to Top

Writing Tests using PHPUnit

Updated 22 February 2024

In previous post PHPUnit Basic Tutorial we learned overview of  PHPUnit.

Now in this post we Write a test class and execute it and read output of test result.
Step 1#: Create a test class named as SampleClass in file named SampleClass.php
this class contain a method for division of two numbers

class SampleClass
    public function divideNumber($a=null,$b=null){
        return $c;


Step 2#:now we write a test named SampleClassTest in file named SampleClassTest.php
for above class


require_once('SampleClass.php');/* include file which you want to test*/
class SampleClassTest extends PHPUnit_Framework_TestCase
    protected $dataarr1=array();
   /* PHPUnit supports sharing the setup code. 
      Before a test method is run, a template 
      method called setUp() is invoked. */
    public function setUp(){
      /*setUp() is where you create the objects against which you will test. */
   /* Once the test method has finished running, 
      whether it succeeded or failed, another template 
      method called tearDown() is invoked. */
    public function tearDown(){ 
    /* tearDown() is where you clean up the objects against which you tested.  */
  /* in below method we pass all element of $this->dataarr1 and counter $i value */
    public function testMyObject(){
        // test to ensure that the object from addNumber  is valid
        $connObj=new SampleClass();/* create object of class which you want to test */
            /*here value of $i is from 1 to 5 so it run successfully*/
           $this->assertTrue($connObj->divideNumber($this->dataarr1[$i],$i) !== false);
   public function testMyObjectnext(){
        $connObj=new SampleClass();
           /*here value of $i is from 0 to 5 so it return error Division by zero  */
           $this->assertTrue($connObj->divideNumber($this->dataarr1[$i],$i) !== false);

For run test class
$ phpunit SampleClassTest.php

PHPUnit 4.7.6 by Sebastian Bergmann and contributors.
Time: 76 ms, Memory: 11.50Mb
There was 1 error:
1) SampleClassTest::testMyObjectnext
Division by zero
Tests: 2, Assertions: 4, Errors: 1.

Start your headless eCommerce
Find out More

test method “testMyObjec()” of class “SampleClassTest” executed successfully so in output we get period (.) that indicate successfully execution of test method.

and for method “testMyObjectnext()” of class “SampleClassTest” execution we get “E” which indicate error occurs while running the test method. also we get detail about error in output.

. . .

Leave a Comment

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


  • webkul
    • yuho
      • webkul
    • yuho
  • yuho
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home