PHPUnit Installation and Use Examples

  • 2021-07-22 09:26:09
  • OfStack

PHPUnit is a testing framework supported by zend. High-quality unit testing is the basis of ensuring project quality, which can effectively reduce BUG and improve procedures.

Install PHPUnit:

Under the directory of php:


pear channel-discover pear;
pear install phpunit/PHPUnit

Under windows, add the environment variable of php to the environment variable of PATH.
Easy to use:


<?php
class StackTest extends PHPUnit_Framework_TestCase
{
 
    public function testArray()
    {
        $stack = array();
        $this->assertEquals(0, count($stack));
 
        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));
 
        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
   
    /**
     * @test
     */
    public function Stringlen()
    {
        $str = 'abc';
        $this->assertEquals(3,  strlen($str));
    }
}

You can see the basic rules of writing PHPUnit from the above:
(1) Tests of class Class are written in ClassTest
(2) ClassTest inherits PHPUnit_Framework_TestCase
(3) The test methods are all in test * format, which can also be labeled as test methods through @ test.
(4) The actual and expected values are asserted by the assertion method assertEquals.


Related articles: