9

首先,我想说 - 我是 PHP (phpunit) 单元测试的新手。在我的新项目(slim3 框架)中,我想测试我的控制器,例如 LoginController。

我的想法是(在单元测试方法中)

  • 创建实例LoginController
  • 在控制器(DI)中模拟一些服务
  • 执行请求的响应方法(在我的控制器方法中__invoke

我的问题是关于__invoke方法的参数。在 Slim3 中,请求的可调用方法有两个第一个参数:

RequestInterface $requestResponseInterface $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;
}

但我不确定这是个好方法。

谢谢你的帮助

4

1 回答 1

19

我在这里写了一个解决方案: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"}');
    }
}
于 2016-03-20T09:16:50.087 回答