当前位置: 首页 > 后端技术 > PHP

在[slim]中伪造请求以执行HTTP测试

时间:2023-03-29 19:56:05 PHP

代码需要做HTTP测试,Laravel内置了这方面的功能。现在要用slim,还得自己动手。网上找了很多例子,但是关于这个方便的例子比较少。然后想到看Laravel的源码,发现其实是伪造了一个Request对象,然后执行返回的结果。然后我也是参考这个在slim中实现构建的测试文件composer.json,添加如下内容自动加载,执行composerdump-auto"autoload-dev":{"psr-4":{"Tests\\":"tests/"}}根目录下新建配置文件phpunit.xml内容如下teststests/bootstrap.php文件内容如下get('/hello/{name}',函数(请求$request,响应$response,数组$args){$name=$args['name'];$response->getBody()->write("Hello,$name");return$response;});$app->get('/api/v1/users',function(请求$request,Response$response){$data=[['name'=>'Bob','age'=>40]];$payload=json_encode($data);$response->getBody()->write($payload);return$response->withHeader('Content-Type','application/json');});//这里不要运行app//$app->run();//并声明一个函数来获取App对象函数getApplication(){全局$app;return$app;}创建一个测试文件tests/HomeTest.php写入内容testHello(){$name='Bob';$serverRequestCreator=ServerRequestCreatorFactory::create();$request=$serverRequestCreator->createServerRequestFromGlobals();$uri=新的Uri();$request=$request->withUri($uri->withPath("/hello/{$name}"));$response=getApplication()->handle($request);$responseContent=(字符串)$response->getBody();$this->assertEquals($responseContent,"你好,{$name}");}publicfunctiontestJsonApi(){$serverRequestCreator=ServerRequestCreatorFactory::create();$request=$serverRequestCreator->createServerRequestFromGlobals();//因为Uri和Request对象不能被修改,所以需要创建它们$uri=newUri();$request=$request->withUri($uri->withPath('api/v1/users'));//如果需要伪造查询参数,可以这样做//$request=$request->withQueryParams([]);//使用全局函数获取App,传入伪造的Request,获取处理后的Response$response=getApplication()->handle($request);//需要用(string)强制转发,不要直接$response->getBody()->getContents()//区别是force-forward,在实现类中将读指针重置到第一个位置,防止完整内容$responseContent=(string)$response->getBody();$this->assertJson($responseContent);}}最后,执行phpunit得到测试结果$phpunitPHPUnit7.5.17bySebastianBergmannandcontributors...2/2(100%)Time:45ms,Memory:4.00MBOK(2tests,2assertions)原文链接http://www.shiguopeng.cn/archives/431