PHP单元测试phpunit

释放双眼,带上耳机,听听看~!

https://phpunit.de/
官方文档下载:
https://phpunit.de/manual/current/zh_cn/phpunit-book.pdf

要进行单元测试的情况,可能有以下三种:

  1. 在开发完成时或开发过程中,对某个函数、方法边调试边进行测试。测试案例可能在进行开发的同时撰写,或者在项目的详细设计阶段即已经写好;
  2. 对一个模块(包含多个功能点)中的所有功能点进行一些集中的测试以检查是不是每一个功能点都能通过测试;
  3. 对于整个项目的统一单元测试。通常与每日构造结合。

安装方法


1
2
3
4
5
1wget https://phar.phpunit.de/phpunit.phar
2chmod +x phpunit.phar
3mv phpunit.phar /usr/local/bin/phpunit
4phpunit --version
5

或者是直接使用


1
2
1php phpunit.phar --version
2

测试用例


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1<?php
2class Money {
3    private $amount;
4
5    public function __construct($amount) {
6        $this->amount = $amount;
7    }
8
9    public function getAmount() {
10        return $this->amount;
11    }
12
13    public function saveAmount($count) {
14        $this->amount += $count;
15        return $this->amount;
16    }
17
18    public function loseAmount($count) {
19        $this->amount = $this->amount - $count;
20        return $this->amount;
21    }
22
23    public function good() {
24        $this->amount + 1000;
25        return $this->amount;
26    }
27}
28

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1<?php
2
3include_once('./Money.php');
4
5use phpunit\framework\TestCase;
6
7class MoneyTest extends TestCase {  
8    public function testGetAmount() {
9        $a = new Money(22);
10        echo $a->getAmount();
11        return ;
12    }
13
14    public function testSaveAmount() {
15        $a = new Money(43);
16        echo $a->saveAmount(20);
17        return ;
18    }
19
20    public function testLoseAmount() {
21        $a = new Money(33);
22        echo $a->loseAmount(1);
23        return ;
24    }
25
26    public function testGood() {
27        $a = new Money(1000);
28        echo $a->good();
29        return ;
30    }
31}
32

1
2
1phpunit MoneyTest.php
2

结果如下


1
2
3
4
5
6
7
8
9
1PHPUnit 5.4.6 by Sebastian Bergmann and contributors.
2
3.22.63.32.                                                                4 / 4 (100%)1000
4
5Time: 173 ms, Memory: 8.00MB
6
7OK (4 tests, 0 assertions)
8
9

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++迭代器

2022-1-11 12:36:11

安全运维

高性能Web服务器Nginx的配置与部署研究(5)Nginx配置符号

2021-8-18 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索