Laravel57单元测试phpunit

50 篇文章 2 订阅

首先进入Laravel57根目录,因为本机没有安装phpunit

phpunit --version

提示未找到命令

实际上Laravel的命令在vendor/bin下
将 phpunit.bat 复制到根目录,并修改第3行,修改后如下:

SET BIN_TARGET=%~dp0/vendor/phpunit/phpunit/phpunit

phpunit --version
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.

在Laravel框架中测试文件夹在根目录下的 tests/

tests/
	Feature/
		ExampleTest.php
	Unit/
		ExampleTest.php
	CreatesApplication.php  可以创建一个app应用
	TestCase.php 	基类,其他的测试文件继承这个类

phpunit配置文件,使用默认即可
phpunit.xml

先清除配置缓存

php artisan config:clear

创建测试类

// 在 Feature 目录下创建一个测试类...
php artisan make:test UserTest

// 在 Unit 目录下创建一个测试类...
php artisan make:test UserTest --unit

执行测试

phpunit tests/Unit/ExampleTest.php

测试用例编写

普通
$this->assertTrue(true);

请求地址
$response = $this->get('/');
$response->assertStatus(200);

设置回话信息
$response = $this->withSession(['foo' => 'bar'])->get('/');

测试json api
$response = $this->json('POST', '/user', ['name' => 'Sally']);
$response->assertStatus(200)->assertJson(['created' => true,]);// 是否存在

精确验证JSON匹配
$response = $this->json('POST', '/user', ['name' => 'Sally']);
$response->assertStatus(200)->assertExactJson(['created' => true,]);

自定义HTTP请求
public function testApplication(){
    $response = $this->call('GET', '/', ['name' => 'Taylor']);
    $this->assertEquals(200, $response->status());
}
。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值