且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

slim3中的控制器单元测试

更新时间:2023-11-17 07:57:28

我在这里写了一个解决方案: 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"}');
    }
}