1. 程式人生 > 程式設計 >PHPUnit 單元測試安裝與使用入門教程

PHPUnit 單元測試安裝與使用入門教程

本文例項講述了PHPUnit 單元測試安裝與使用。分享給大家供大家參考,具體如下:

一、官網下載對應 PHP 版本的程式碼庫

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

PHPUnit 單元測試安裝與使用入門教程

二、安裝 PHPUnit

官網提供了兩種方法安裝

1.PHP Archive (PHAR)

➜ 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

➜ composer require --dev phpunit/phpunit ^8

➜ ./vendor/bin/phpunit --version
PHPUnit 8.0.0 by Sebastian Bergmann and contributors.

三、使用 PHPUnit 進行測試,以下程式碼預設你是使用Composer 安裝的 PHPUnit

安裝完成後在當前目錄下新增檔案EmailTest.php,檔案內容如下

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class EmailTest extends TestCase
{
  public function testCanBeCreatedFromValidEmailAddress(): void
  {
    $this->assertInstanceOf(
      Email::class,Email::fromString('[email protected]')
    );
  }

  public function testCannotBeCreatedFromInvalidEmailAddress(): void
  {
    $this->expectException(InvalidArgumentException::class);

    Email::fromString('invalid');
  }

  public function testCanBeUsedAsString(): void
  {
    $this->assertEquals(
      '[email protected]',Email::fromString('[email protected]')
    );
  }
}

執行測試

➜ ./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相關內容感興趣的讀者可檢視本站專題:《PHP錯誤與異常處理方法總結》、《php字串(string)用法總結》、《PHP陣列(Array)操作技巧大全》、《PHP運算與運算子用法總結》、《PHP網路程式設計技巧總結》、《PHP基本語法入門教程》、《php面向物件程式設計入門教程》及《php優秀開發框架總結》

希望本文所述對大家PHP程式設計有所幫助。