1、配置单元测试目录:
(1)autoload.PHP
<?PHP function autoloader($dir){ spl_autoload_register(function($name) use ($dir){ $name = str_replace(‘\\‘,DIRECTORY_SEPARATOR,$name); require $dir.DIRECTORY_SEPARATOR.$name.‘.PHP‘; }); } define(‘ROOT‘,__DIR__); autoloader(ROOT);
(2)Money.PHP
<?PHP class Money { private $amount; public function __construct($amount) { $this->amount = $amount; } public function getAmount() { return $this->amount; } public function negate() { return new Money(-1*$this->amount); } }
(3)MoneyTest.PHP
<?PHP use PHPUnit\Framework\TestCase; class MoneyTest extends TestCase { public function testCanBeNegated() { $a = new Money(1); $b = $a->negate(); $this->assertEquals(-1,$b->getAmount()); } }
2、配置测试框架
3、建立单元测试模板:
4、运行测试:
5、测试结果
6、PHPunit中相关的几个断言:
AssertTrue/AssertFalse 断言是否为真值还是假 AssertEquals 判断输出是否和预期的相等 AssertGreaterThan 断言结果是否大于某个值,同样的也有LessThan(小于),GreaterThanOrEqual(大于等于), LessThanOrEqual (小于等于). AssertContains 判断输入是否包含指定的值 AssertType 判断是否属于指定类型 AssertNull 判断是否为空值 AssertFileExists 判断文件是否存在 AssertRegExp 根据正则表达式判断
7、注意事项
(1)测试用例要引入PHPunit
use PHPUnit\Framework\TestCase;
(2)测试类要继承TestCase
class MoneyTest extends TestCase参考:https://blog.51cto.com/12173069/2317104