💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 概述 tp6 支持支持直接使用 phpunit 的单元测试 安装 ``` composer require --dev phpunit/phpunit ``` 使用 <details> <summary>/test/DemoTest.php</summary> ``` <?php declare (strict_types=1); namespace tests; final class DemoTest extends \PHPUnit\Framework\TestCase { /** * 这里是测试控制的某个方法产出的结果 * * @test */ public function testControllerDemo(): void { $request = new \app\Request(); $request->setMethod('POST'); // 路由地址 $request->setUrl('/index/home'); //$request->withGet(['xid' => 99,]); //$request->withPost(['aaa' => 111, 'bbb' => 222,]); $request->withHeader(['HTTP_ACCEPT' => 'application/json',]); // 初始化框架,并将请求信息类注入到框架里面 $app = (new \think\App()); $app->http->run($request); // 调用框架方法,这里可以按命名空间直接调用 $userController = new UserController($app); // 请求接口的控制器方法 $response = $userController->index(); // 获取接口返回得body内容 $content = $response->getContent(); // 可以进行你的断言操作了 $this->assertEquals("success", $content); } /** * @test */ public function testDemo1(): void { //断言为真 $this->assertTrue(true); } } ``` </details> <br/> 实际的例子 <details> <summary>/test/DemoTest.php</summary> ``` <?php declare (strict_types=1); namespace tests; use app\admin\controller\v1\Login; use app\common\services\User; use PHPUnit\Framework\TestCase; use think\App; class UserTest extends TestCase{ private $app; protected function setUp(): void{ parent::setUp(); $this->app=new App(); $this->app->http->run(); } /** * 测试service * @return void */ public function testLogin(): void { $user = new User(new \app\common\model\User(),new \app\common\validate\User()); // 测试正常登录 $res = $user->login("superadmin","123456"); if($res===false){ $this->expectErrorMessage($user->getErr()); } $this->assertEquals("superadmin",$res['login_name']); // 测试异常 $checkData=[ '测试账号不存在'=>['superadmin1','123456','账号不存在'], '测试密码不正确'=>['superadmin','123456','密码不正确'], '测试站字段为空'=>['','123456','账号字段为空'], '测试密码字段为空'=>['superadmin','','密码字段为空'], ]; foreach($checkData as $item){ $res = $user->login($item[0],$item[1]); if($res===false){ $this->assertEquals($item[2],$user->getErr()); } } } /** * 测试控制器 * @return void */ public function testLoginApi():void{ //由于 functions.php 无法自定自定引入 require_once __DIR__.'/../app/admin/config/functions.php'; $request = new \app\Request(); $request->setMethod('POST'); // 路由地址 $request->setUrl('/v1/admin/login/login'); $request->withPost([ 'login_name'=>'superadmin', 'password'=>'123456', ]); $this->app->http->run($request); $login = new Login($this->app); $service = new User(new \app\common\model\User(), new \app\common\validate\User()); $res = $login->login($service); $resArr =$res->getData(); $this->assertEquals(0,$resArr['code']); $this->assertEquals("登录成功",$resArr['msg']); $this->assertEquals("superadmin",$resArr['data']['login_name']); } } ``` </details> <br/>