当前位置: 移动技术网 > IT编程>开发语言>PHP > PHPUnit 单元测试安装与使用入门教程

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

2020年06月23日  | 移动技术网IT编程  | 我要评论

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

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

二、安装 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)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网