当前位置:首页 > PHP教程 > php应用 > 列表

PHPUnit 单元测试安装与使用入门教程

发布:smiling 来源: PHP粉丝网  添加日期:2022-03-01 09:33:03 浏览: 评论:0 

本文实例讲述了PHPUnit 单元测试安装与使用,分享给大家供大家参考,具体如下:

一、官网下载对应 PHP 版本的代码库

https://phpunit.de/getting-started-with-phpunit.html

二、安装 PHPUnit

官网提供了两种方法安装

1. PHP Archive (PHAR)

  1. ➜ wget -O phpunit https://phar.phpunit.de/phpunit-8.phar 
  2.  
  3. ➜ chmod +x phpunit 
  4.  
  5. ➜ ./phpunit --version 
  6. PHPUnit 8.0.0 by Sebastian Bergmann and contributors. 
  7. ➜ wget -O phpunit https://phar.phpunit.de/phpunit-8.phar 
  8.  
  9. ➜ chmod +x phpunit 
  10.  
  11. ➜ ./phpunit --version 
  12. PHPUnit 8.0.0 by Sebastian Bergmann and contributors. 

2. Composer

  1. ➜ composer require --dev phpunit/phpunit ^8 
  2.  
  3. ➜ ./vendor/bin/phpunit --version 

PHPUnit 8.0.0 by Sebastian Bergmann and contributors.

三、使用 PHPUnit 进行测试,以下代码默认你是使用 Composer 安装的 PHPUnit

安装完成后在当前目录下添加文件 EmailTest.php,文件内容如下

  1. <?php 
  2. declare(strict_types=1); 
  3.  
  4. use PHPUnit\Framework\TestCase; 
  5.  
  6. final class EmailTest extends TestCase 
  7. { 
  8.   public function testCanBeCreatedFromValidEmailAddress(): void 
  9.   { 
  10.     $this->assertInstanceOf( 
  11.       Email::class, 
  12.       Email::fromString('user@example.com') 
  13.     ); 
  14.   } 
  15.  
  16.   public function testCannotBeCreatedFromInvalidEmailAddress(): void 
  17.   { 
  18.     $this->expectException(InvalidArgumentException::class); 
  19.  
  20.     Email::fromString('invalid'); 
  21.   } 
  22.  
  23.   public function testCanBeUsedAsString(): void 
  24.   { 
  25.     $this->assertEquals( 
  26.       'user@example.com', 
  27.       Email::fromString('user@example.com') 
  28.     ); 
  29.   } 
  30. } 

运行测试

  1. ➜ ./vendor/bin/phpunit --bootstrap vendor/autoload.php tests/EmailTest 
  2. PHPUnit 8.0.0 by Sebastian Bergmann and contributors. 
  3.  
  4. ...                                 3 / 3 (100%) 
  5.  
  6. Time: 70 ms, Memory: 10.00MB 
  7.  
  8. OK (3 tests, 3 assertions)

Tags: PHPUnit单元测试 PHPUnit安装

分享到:

相关文章