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

2022-04-15 0 701

本文实例讲述了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('user@example.com')
    );
  }

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

    Email::fromString('invalid');
  }

  public function testCanBeUsedAsString(): void
  {
    $this->assertEquals(
      'user@example.com',
      Email::fromString('user@example.com')
    );
  }
}

运行测试

 ./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相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 PHPUnit 单元测试安装与使用入门教程 https://www.niceym.com/15244.html