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

<?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优秀开发框架总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f468ee17be26dd2821a1bf4463a79ba3.html