首先,我想说 - 我是 PHP (phpunit) 单元测试的新手。
在我的新项目(slim3 框架)中,我想测试我的 Controller ,例如 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;
}
但我不确定这是个好方法。
谢谢你的帮助
最佳答案
我在这里写了一个解决方案:https://akrabat.com/testing-slim-framework-actions/
我用 Environment::mock()
创建 $request
然后我可以运行该操作。使每个路由都可以调用一个类,其中所有依赖项都注入(inject)到构造函数中,这也使这一切变得更加容易。
本质上,测试如下所示:
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"}');
}
}
关于phpunit - slim3 中的 Controller 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36107883/