一、PHPUnit简介
PHPUnit是一个面向PHP程序员的测试框架,这是一个xUnit的体系结构的单元测试框架。
参考官方文档地址:PHPUnit文档 - PHP测试框架
phpunit.phar下载地址:https://phar.phpunit.de/,与PHP版本兼容性如下:(下载对应的兼容版本即可)

用 PHPUnit 编写测试的基本惯例与步骤:
- 针对类
的测试写在类Class
中。ClassTest
-
(通常)继承自ClassTest
。PHPUnit\Framework\TestCase
- 测试都是命名为
test*
的公用方法。
也可以在方法的文档注释块(docblock)中使用
标注将其标记为测试方法。@test
- 在测试方法内,类似于
(断言可参见 附录 A.断言)这样的断言方法用来对实际值与预期值的匹配做出断言。assertEquals()
二、PhpStorm配置使用PHPUnit
1、配置phpunit.phar
2、配置phpunit的依赖,phpunit依赖可在github上下载
3、编写正确的断言单元测试代码
<?php
class TestAssertCase extends \PHPUnit\Framework\TestCase {
/**
* This method is called before each test.
*/
public function setUp(): void {
echo "This method is called before each test.\n";
}
/**
* This method is called after each test.
*/
public function tearDown(): void {
echo "This method is called after each test.\n";
}
/**
* @dataProvider dataProvider
* @param string $a
* @param string $str
*/
public function testAssert(string $a, string $str) {
echo "This testAssert() is start.\n";
$this->assertStringContainsString($a, $str);
echo "This testAssert() is end.\n";
}
public function dataProvider() {
return [
["a", "abc"]
];
}
}
4、执行测试用例:可使用 Run 'TestAssertCase (PHPUnit)' 或者 Debug 'TestAssertCase (PHPUnit)' 运行
5、执行结果:输出OK
6、编写一个错误的断言测试:使用@test注解
<?php
class TestAssertCase extends \PHPUnit\Framework\TestCase {
/**
* This method is called before each test.
*/
public function setUp(): void {
echo "This method is called before each test.\n";
}
/**
* This method is called after each test.
*/
public function tearDown(): void {
echo "This method is called after each test.\n";
}
/**
* @dataProvider dataProvider
* @param string $a
* @param string $str
* @test
*/
public function TestAssert(string $a, string $str) {
echo "This testAssert() is start.\n";
$this->assertStringContainsString($a, $str);
echo "This testAssert() is end.\n";
}
public function dataProvider() {
return [
["A", "abc"]
];
}
}
7、执行结果:输出错误信息