本文實例講述了PHPUnit 單元測試安裝與使用。分享給大家供大家參考,具體如下:
一、官網下載對應 PHP 版本的代碼庫
https://phpunit.de/getting-started-with-phpunit.html
二、安裝 PHPUnit
官網提供了兩種方法安裝
1. PHP Archive (PHAR)
1
2
3
4
5
6
|
? wget -O phpunit https: //phar .phpunit.de /phpunit-8 .phar ? chmod +x phpunit ? . /phpunit --version PHPUnit 8.0.0 by Sebastian Bergmann and contributors. |
2. Composer
1
2
3
4
|
? composer require --dev phpunit /phpunit ^8 ? . /vendor/bin/phpunit --version PHPUnit 8.0.0 by Sebastian Bergmann and contributors. |
三、使用 PHPUnit 進行測試,以下代碼默認你是使用 Composer 安裝的 PHPUnit
安裝完成后在當前目錄下添加文件 EmailTest.php,文件內容如下
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
|
<?php declare (strict_types=1); use PHPUnit\Framework\TestCase; final class EmailTest extends TestCase { public function testCanBeCreatedFromValidEmailAddress(): void { $this ->assertInstanceOf( Email:: class , ); } public function testCannotBeCreatedFromInvalidEmailAddress(): void { $this ->expectException(InvalidArgumentException:: class ); Email::fromString( 'invalid' ); } public function testCanBeUsedAsString(): void { $this ->assertEquals( ); } } |
運行測試
1
2
3
4
5
6
7
8
|
? . /vendor/bin/phpunit --bootstrap vendor /autoload .php tests /EmailTest PHPUnit 8.0.0 by Sebastian Bergmann and contributors. ... 3 / 3 (100%) Time: 70 ms, Memory: 10.00MB OK (3 tests, 3 assertions) |
希望本文所述對大家PHP程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/ryanzheng/p/11951286.html