PHP单元测试PHPUnit

本文介绍如何在Windows环境下为PHP项目安装并使用PHPUnit进行单元测试的过程。包括PHPUnit的下载、安装配置步骤及环境变量设置方法,同时提供了一个简单的测试案例。

windows开发环境下,PHP使用单元测试可以使用PHPUnit。

安装

首先下载PHPUnit,官网:https://phpunit.de/  根据自己的PHP版本下载对应的PHPUnit版本,我本地是PHP5.5,所以这里我下载PHPUnit4.8。下载完成得到phpunit-4.8.35.phar文件,放到任意目录,这边我放到D:\phpunit下,并把文件名改为:phpunit.phar  。配置环境变量:右击我的电脑-》属性-》高级系统设置-》环境变量-》编辑path在最后添加phpunit.phar的路径,这里我是D:\phpunit,所以在最后添加D:\phpunit  。

打开命令行win+R输入cmd,进入到D:\phpunit

cd /d D:\phpunit
安装phpunit

echo @php "%~dp0phpunit.phar" %* > phpunit.cmd
查看是否安装成功

phpunit --version
如果显示phpunit的版本信息,说明安装成功了,这边我显示:PHPUnit 4.8.35 by Sebastian Bergmann and contributors.

测试

先写一个需要测试的类,该类有一个eat方法,方法返回字符串:eating,文件名为Human.php

<?php

class Human
{
	public function eat()
	{
		return 'eating';
	}
}
再写一个phpunit的测试类,测试Human类的eat方法,必须引入Human.php文件、phpunit,文件名为test1.php

<?php

include 'Human.php';

use PHPUnit\Framework\TestCase;
    class TestHuman extends TestCase
    {
        public function testEat()
        {
        	$human = new Human;
        	$this->assertEquals('eating', $human->eat());
        }
    }
?>
其中assertEquals方法为断言,判断eat方法返回是否等于'eating',如果返回一直则成功否则返回错误,运行测试:打开命令行,进入test1.php的路径,然后运行测试:

phpunit test1.php
返回信息:

PHPUnit 4.8.35 by Sebastian Bergmann and contributors.

.

Time: 202 ms, Memory: 14.75MB

OK (1 test, 1 assertion)
则表示断言处成功,即返回值与传入的参数值一致。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值