slim3中的控制器单元测试 [英] Controller unit test in slim3
问题描述
首先,我想说-我是PHP(phpunit)单元测试的新手. 在我的新项目(slim3框架)中,我想测试我的控制器,例如LoginController.
At the outset, I would like to say - I'm new in unit testing in PHP (phpunit). In my new project (slim3 framework) I would like to test my controllers for example LoginController.
我的想法是(在单元测试方法中)
My idea is (in unit test method)
- 创建
LoginController
的实例
- 模拟控制器(DI)中的某些服务
- 执行方法,该方法是对请求的响应(在我的控制器中,方法为
__invoke
)
- Create instance of
LoginController
- Mock some services in controller (DI)
- Execute method which is response for request (in my controllers method
__invoke
)
我的问题是关于__invoke
方法的参数.
在Slim3中,请求的可调用方法具有两个第一个参数:
My problem is about parameters for __invoke
method.
In Slim3 callable method for request has two first params:
RequestInterface $request
和ResponseInterface $response
如何在单元测试课程中创建此参数?我正在寻找有关此问题的一些示例,但没有成功.
How can I create this parameters in my unit test class? I was searching for some examples for this issue but without success.
有什么建议吗?
我在Slim3测试中找到了一些代码来模拟请求:
I've found some code in Slim3 tests to mock request:
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;
}
但是我不确定这是个好方法.
But I'm not sure that is good way.
感谢您的帮助
推荐答案
我在这里写了一个解决方案: https://akrabat.com/testing-slim-framework-actions/
I wrote up one solution here: https://akrabat.com/testing-slim-framework-actions/
我使用Environment::mock()
创建一个$request
,然后可以运行该动作.使每个路由都可调用为一个将所有依赖项都注入到构造函数的类,这也使这一切变得更加容易.
I use Environment::mock()
to create a $request
and then I can run the action. Making each route callable a class where all dependencies are injected into the constructor makes this all much easier too.
本质上,测试看起来像这样:
Essentially, a test looks like this:
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"}');
}
}
这篇关于slim3中的控制器单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!