2016-03-19 64 views
4

首先,我想說 - 我是PHP(phpunit)單元測試新手。 在我的新項目(slim3框架)中,我想測試我的控制器,例如LoginController。slim3控制器單元測試

我的想法是(在單元測試方法)

  • 在控制器創建的LoginController
  • 模擬一些服務實例(DI)
  • 執行方法,該方法是用於請求響應(在我的控制器方法__invoke

我的問題是關於__invoke方法的參數。 在Slim3可調用的方法要求有兩個第一PARAMS:

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; 
} 

但我不知道這是很好的方式。

感謝所有幫助

回答

10

我寫了一個解決方案在這裏: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"}'); 
    } 
} 
+0

這個工作對我來說太棒了!感謝@rob(在您的網站上寫出的解決方案也有幫助) –

+0

感謝此代碼,@ rob-allen!如果我們的路線是通過匿名函數定義的,你會如何建議我們做類似的事情? (例如:'$ app-> get(「/ test/{id}」,function($ request,$ response,$ args){...});') – rinogo

+0

我想通了。對於那些好奇的人,你需要將你的匿名函數轉換成命名函數(例如'echo_action()')。然後,使用'$ action =「echo_action」;' – rinogo