rob*_*rtw 8 phpunit slim slim-3
首先,我想说 - 我是用PHP(phpunit)进行单元测试的新手.在我的新项目(slim3框架)中,我想测试我的控制器,例如LoginController.
我的想法是(在单元测试方法中)
LoginController__invoke)我的问题是关于__invoke方法的参数.在Slim3中,可调用的请求方法有两个第一个参数:
RequestInterface $request 和 ResponseInterface $response
如何在单元测试类中创建此参数?我正在寻找这个问题的一些例子,但没有成功.
有什么建议?
我在Slim3测试中发现了一些模拟请求的代码:
protected function requestFactory()
{
$uri = Uri::createFromString('https://example.com:443/foo/bar?abc=123');
$headers = new Headers();
$cookies = array(
'user' => 'john',
'id' => '123',
);
$env = Slim\Http\Environment::mock();
$serverParams = $env->all();
$body = new Body(fopen('php://temp', 'r+'));
$request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body);
return $request;
}
Run Code Online (Sandbox Code Playgroud)
但我不确定这是好方法.
谢谢你的帮助
Rob*_*len 17
我在这里写了一个解决方案:https://akrabat.com/testing-slim-framework-actions/
我Environment::mock()用来创建一个$request然后我可以运行该动作.使每个路由可调用一个类,其中所有依赖项都被注入到构造函数中,这使得这一切变得更加容易.
基本上,测试看起来像这样:
class EchoActionTest extends \PHPUnit_Framework_TestCase
{
public function testGetRequestReturnsEcho()
{
// instantiate action
$action = new \App\Action\EchoAction();
// We need a request and response object to invoke the action
$environment = \Slim\Http\Environment::mock([
'REQUEST_METHOD' => 'GET',
'REQUEST_URI' => '/echo',
'QUERY_STRING'=>'foo=bar']
);
$request = \Slim\Http\Request::createFromEnvironment($environment);
$response = new \Slim\Http\Response();
// run the controller action and test it
$response = $action($request, $response, []);
$this->assertSame((string)$response->getBody(), '{"foo":"bar"}');
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4091 次 |
| 最近记录: |