首页 > 代码库 > PHP PHPUnit的简单使用

PHP PHPUnit的简单使用

1.window安装pear的教程:http://jingyan.baidu.com/article/ca41422fd8cf3d1eae99ed3e.html

2.在工作目录下,放两个文件:

1)Calculator.php

技术分享
 1 <?php
 2 
 3 class Calculator{
 4 
 5     public function add($a,$b){
 6         return $a + $b;
 7     }
 8 
 9     public function sub($a,$b){
10         return $a - $b;
11     }
12 }
View Code

2)CalculatorTest.php

技术分享
 1 <?php
 2 
 3 //PEAR安装在系统中
 4 require "PHPUnit/TestCase.php";
 5 require "Calculator.php";
 6 
 7 class CalculatorTest extends PHPUnit_Framework_TestCase{
 8     private $calculator;
 9 
10     function setUp()
11     {
12         parent::setUp(); // TODO: Change the autogenerated stub
13         $this->calculator = new Calculator();
14     }
15 
16     function tearDown()
17     {
18         parent::tearDown(); // TODO: Change the autogenerated stub
19         unset($this->calculator);
20     }
21 
22     public function testAddBothPositive(){
23         $result = $this->calculator->add(3,4);
24         $this->assertEquals(8,$result);
25     }
26 
27     public function testAddPositiveAndNegative(){
28         $result = $this->calculator->add(3,-4);
29         $this->assertEquals(-1,$result);
30     }
31 
32     public function testAddNegativeAndPositive(){
33         $result = $this->calculator->add(-4,3);
34         $this->assertEquals(-1,$result);
35     }
36 
37     public function testAddPositiveAndZero(){
38         $result = $this->calculator->add(5,0);
39         $this->assertEquals(5,$result);
40     }
41 
42     public function testAddNegativeAndZero(){
43         $result = $this->calculator->add(-5,0);
44         $this->assertEquals(-5,$result);
45     }
46 
47     public function testAddNegativeAndNegative(){
48         $result = $this->calculator->add(-5,-5);
49         $this->assertEquals(-10,$result);
50     }
51 }
View Code

当前工作目录下,在控制台运行 : phpunit  CalculatorTest

注意:如果出现找不到PHPUnit相关的头文件,可以用在相关文件输出get_include_path()的结果查看. 在php.ini 可以找 “”include_path" 关键字,定位原因。

3. 在安装XDebug的前提下,可以运行:phpunit  --coverage-html  "OUTPUT_PATH"  CalculatorTest ,生成一个报表,HTML格式,可以了解此次测试代码的覆盖率。

 

PHP PHPUnit的简单使用