欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-22 12:40:04
本文实例讲述了phpunit 单元测试安装与使用。分享给大家供大家参考,具体如下:一、官网下载对应 php 版本的代码库二、安装 phpunit官网提供了两种方法安装1.php archive (ph...

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

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

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)