Laravel 中集成了PHPUnit进行单元测试,实际上,使用PHPUnit进行单元测试在Laravel中是开箱即用的,测试的配置文件为根目录下的phpunit.xml
,该配置文件为咱们作好了全部配置工做:php
<?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" bootstrap="bootstrap/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false"> <testsuites> <testsuite name="Application Test Suite"> <directory>./tests/</directory> </testsuite> </testsuites> <filter> <whitelist> <directory suffix=".php">app/</directory> </whitelist> </filter> <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> </php> </phpunit>
testsuites
中定义了测试文件存放路径为根目录下的tests
目录。html
filter
中定义了须要进行单元测试的PHP文件存放位置。python
php
中配置了测试环境的环境变量,默认APP_ENV为testing
,缓存驱动被设置为array
,Session驱动被设置为array
,队列驱动被设置为sync
。laravel
使用Laravel的测试功能以前须要先安装PHPUnit,以Homestead虚拟机为例,安装步骤以下:shell
wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar sudo mv phpunit.phar /usr/local/bin/phpunit
而后查看PHPUnit的版本验证是否安装成功:bootstrap
phpunit --version
PHPUnit x.y.z by Sebastian Bergmann and contributors.windows
总体上说,在 Windows 下安装 PHAR 和手工在 Windows 下安装 Composer 是同样的过程:缓存
为 PHP 的二进制可执行文件创建一个目录,例如 C:\bin
app
将 ;C:\bin
附加到 PATH
环境变量中(相关帮助)composer
下载 https://phar.phpunit.de/phpunit.phar 并将文件保存到 C:\bin\phpunit.phar
打开命令行(例如,按 Windows+R » 输入 cmd
» ENTER)
创建外包覆批处理脚本(最后获得 C:\bin\phpunit.cmd
):
C:\Users\username> cd C:\bin C:\bin> echo @php "%~dp0phpunit.phar" %* > phpunit.cmd C:\bin> exit
6.新开一个命令行窗口,确认一下能够在任意路径下执行 PHPUnit:
C:\Users\username> phpunit --versionPHPUnit x.y.z by Sebastian Bergmann and contributors.
参考:
https://phpunit.de/manual/current/zh_cn/installation.html#installation.phar.windows
接下来咱们使用Laravel提供的ExampleTest.php
实现简单单元测试,首先咱们修改tests
目录下的ExampleTest.php
文件以下:
<?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class ExampleTest extends TestCase { /** * A basic functional test example. * * @return void */ public function testBasicExample() { $this->visit('/') ->see('Laravel学院'); } }
其中visit
方法用于访问指定路由页面,see
方法则判断返回响应中是否包含指定字符串。
而后在routes.php
中确保包含以下路由(若是没有的话添加该路由):
Route::get('/',function(){ return view('welcome'); });
访问http://laravel.app:8000/
,页面显示以下内容:
而后到项目根目录下运行以下命令:
phpunit
输出结果以下:
表示测试经过。
接下来咱们修改ExampleTest.php
测试方法以下:
public function testBasicExample() { $this->visit('/') ->see('LaravelAcademy'); }
再次运行phpunit
,则显示测试失败信息(部分截图):
……
测试结果会显示错误数目,错误位置及错误缘由,方便咱们快速定位错误并进行修复。