SoFunction
Updated on 2025-03-09

PHPUnit installation and usage examples

PHPUnit is a testing framework that is strongly supported by zend. It ensures project quality during high-quality unit testing, and can effectively reduce bugs and improve programs.

Install PHPUnit:

In the php directory:

Copy the codeThe code is as follows:

pear channel-discover pear;
pear install phpunit/PHPUnit

In Windows, add the PHP environment variable to the PATH environment variable.
Simple use:

Copy the codeThe code is as follows:

<?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));
    }
}

From the above, you can see the basic rules for writing PHPUnit:
(1) Class Class test is written in ClassTest
(2) ClassTest inherits PHPUnit_Framework_TestCase
(3) The test methods are all in the test* format, and they can also be marked as test methods through @test.
(4) Assert the actual value and the expected value through the assert method assertEquals.