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

PHP单元测试框架PHPUnit用法详解

程序员文章站 2023-10-20 23:31:30
本文实例讲述了php单元测试框架phpunit用法。分享给大家供大家参考,具体如下: 以前在学习ios开发时有专门写过objective-c的单元测试的文章,ios开...

本文实例讲述了php单元测试框架phpunit用法。分享给大家供大家参考,具体如下:

以前在学习ios开发时有专门写过objective-c的单元测试的文章,ios开发学习之单元测试,今天再总结下怎么在php中使用单元测试。

一、前言

在这篇文章中,我们使用 composer 的依赖包管理工具进行phpunit包安装和管理,composer 官方地址 https://getcomposer.org/,按照提示进行全局安装即可,另外,我们也会使用一个非常好用的monolog记录日志组件记录日志,方便我们查看。

在根目录下建立 coomposer.json 的配置文件,输入以下内容:

{
  "autoload": {
    "classmap": [
      "./"
    ]
  }
}

上面的意思是将根目录下的所有的类文件都加载进来, 在命令行执行 composer install 后,在根目录会生成出一个vendor的文件夹,我们以后通过 composer 安装的任何第三方代码都会被生成在这里。

二、为什么要单元测试?

只要你想到输入一些东西到print语句或调试表达式中,就用测试代替它。 --martin fowler

phpunit 是一个用php编程语言开发的开源软件,是一个单元测试框架。phpunit由sebastian bergmann创建,源于kent beck的sunit,是xunit家族的框架之一。

单元测试是对单独的代码对象进行测试的过程,比如对函数、类、方法进行测试。单元测试可以使用任意一段已经写好的测试代码,也可以使用一些已经存在的测试框架,比如junit、phpunit或者cantata++,单元测试框架提供了一系列共同、有用的功能来帮助人们编写自动化的检测单元,例如检查一个实际的值是否符合我们期望的值的断言。单元测试框架经常会包含每个测试的报告,以及给出你已经覆盖到的代码覆盖率。

总之一句话,使用 phpunit 进行自动测试,会使你的代码更健壮,减少后期维护的成本,也是一种比较标准的规范,现如今流行的php框架都带了单元测试,如laraval,symfony,yii2等,单元测试已经成了标配。

另外,单元测试用例是通过命令操控测试脚本的,而不是通过浏览器访问url的。

三、安装phpunit

使用 composer 方式安装 phpunit,其他安装方式请看这里

composer require --dev phpunit/phpunit ^6.2

安装 monolog 日志包,做 phpunit 测试记录日志用。

composer require monolog/monolog

安装好之后,我们可以看coomposer.json 文件已经有这两个扩展包了:

"require": {
  "monolog/monolog": "^1.23",
  },
"require-dev": {
    "phpunit/phpunit": "^6.2"
  },

四、phpunit简单用法

1、单个文件测试

创建目录tests,新建文件 stacktest.php,编辑如下:

<?php
/**
 * 1、composer 安装monolog日志扩展,安装phpunit单元测试扩展包
 * 2、引入autoload.php文件
 * 3、测试案例
 *
 *
 */
namespace app\tests;
require_once __dir__ . '/../vendor/autoload.php';
define("root_path", dirname(__dir__) . "/");
use monolog\logger;
use monolog\handler\streamhandler;
use phpunit\framework\testcase;
class stacktest extends testcase
{
  public function testpushandpop()
  {
    $stack = [];
    $this->assertequals(0, count($stack));
    array_push($stack, 'foo');
    // 添加日志文件,如果没有安装monolog,则有关monolog的代码都可以注释掉
    $this->log()->error('hello', $stack);
    $this->assertequals('foo', $stack[count($stack)-1]);
    $this->assertequals(1, count($stack));
    $this->assertequals('foo', array_pop($stack));
    $this->assertequals(0, count($stack));
  }
  public function log()
  {
    // create a log channel
    $log = new logger('tester');
    $log->pushhandler(new streamhandler(root_path . 'storage/logs/app.log', logger::warning));
    $log->error("error");
    return $log;
  }
}

代码解释:

stacktest为测试类

stacktest 继承于 phpunit\framework\testcase

测试方法testpushandpop(),测试方法必须为public权限,一般以test开头,或者你也可以选择给其加注释@test来表

在测试方法内,类似于 assertequals() 这样的断言方法用来对实际值与预期值的匹配做出断言。

命令行执行:

phpunit 命令 测试文件命名

➜ framework# ./vendor/bin/phpunit tests/stacktest.php
// 或者可以省略文件后缀名
// ./vendor/bin/phpunit tests/stacktest

执行结果:

➜  framework# ./vendor/bin/phpunit tests/stacktest.php
phpunit 6.4.1 by sebastian bergmann and contributors.
.                                                                   1 / 1 (100%)
time: 56 ms, memory: 4.00mb
ok (1 test, 5 assertions)

我们可以在app.log文件中查看我们打印的日志信息。

2、类文件引入

calculator.php

<?php
class calculator
{
  public function sum($a, $b)
  {
    return $a + $b;
  }
}
?>

单元测试类:

calculatortest.php

<?php
namespace app\tests;
require_once __dir__ . '/../vendor/autoload.php';
require "calculator.php";
use phpunit\framework\testcase;
class calculatortest extends testcase
{
  public function testsum()
  {
    $obj = new calculator;
    $this->assertequals(0, $obj->sum(0, 0));
  }
}

命令执行:

> ./vendor/bin/phpunit tests/calculatortest

执行结果:

phpunit 6.4.1 by sebastian bergmann and contributors.
f                                                                   1 / 1 (100%)
time: 117 ms, memory: 4.00mb
there was 1 failure:

如果我们把这里的断言故意写错,$this->assertequals(1, $obj->sum(0, 0));

看执行结果:

phpunit 6.4.1 by sebastian bergmann and contributors.
f                                                                   1 / 1 (100%)
time: 117 ms, memory: 4.00mb
there was 1 failure:
1) app\tests\calculatortest::testsum
failed asserting that 0 matches expected 1.
/applications/xampp/xamppfiles/htdocs/web/framework/tests/calculatortest.php:22
failures!
tests: 1, assertions: 1, failures: 1.

会直接报出方法错误信息及行号,有助于我们快速找出bug

3、高级用法

你是否已经厌烦了在每一个测试方法命名前面加一个test,是否因为只是调用的参数不同,却要写多个测试用例而纠结?我最喜欢的高级功能,现在隆重推荐给你,叫做框架生成器。

calculator.php

<?php
class calculator
{
  public function sum($a, $b)
  {
    return $a + $b;
  }
}
?>

命令行启动测试用例,使用关键字 --skeleton

> ./vendor/bin/phpunit --skeleton calculator.php

执行结果:

phpunit 6.4.1 by sebastian bergmann and contributors.
wrote test class skeleton for calculator to calculatortest.php.

是不是很简单,因为没有测试数据,所以这里加测试数据,然后重新执行上边的命令

<?php
class calculator
{
  /**
   * @assert (0, 0) == 0
   * @assert (0, 1) == 1
   * @assert (1, 0) == 1
   * @assert (1, 1) == 2
   */
  public function sum($a, $b)
  {
    return $a + $b;
  }
}
?>

原始类中的每个方法都进行@assert注解的检测。这些被转变为测试代码,像这样

/**
 * generated from @assert (0, 0) == 0.
 */
public function testsum() {
  $obj = new calculator;
  $this->assertequals(0, $obj->sum(0, 0));
}

执行结果:

./vendor/bin/phpunit tests/calculatortest
phpunit 6.4.1 by sebastian bergmann and contributors.
....
time: 0 seconds
ok (4 tests)

更多关于php相关内容感兴趣的读者可查看本站专题:《php错误与异常处理方法总结》、《php字符串(string)用法总结》、《php数组(array)操作技巧大全》、《php运算与运算符用法总结》、《php网络编程技巧总结》、《php基本语法入门教程》、《php面向对象程序设计入门教程》及《php优秀开发框架总结

希望本文所述对大家php程序设计有所帮助。