2013-01-10 61 views
1

我想創建一個簡單的訪問單元測試,如圖所示in the tutorialZend Framework 2 - 單元測試

我的項目使用ZFCUser進行驗證。

結果我的(顯然沒有經過認證)測試儀獲得的302 HTTP response,而不是預期的200

任何想法,我能做些什麼呢?謝謝!

從本教程中的代碼如下所示:

public function testAddActionCanBeAccessed() 
{ 
    $this->routeMatch->setParam('action', 'add'); 

    $result = $this->controller->dispatch($this->request); 
    $response = $this->controller->getResponse(); 

    $this->assertEquals(200, $response->getStatusCode()); 
} 
+0

保護你測試的代碼;)(即使我不能幫助,其他人可能會看到你的測試) – Sam

+0

正如我所說,現在它是一個非常簡單的測試。我只需要繞過測試人員的身份驗證...併爲此問題,我沒有任何代碼;) – Ron

+0

你想測試什麼?你的'添加'行動可以完成**當驗證**?然後你必須模擬身份驗證服務並在其中放置身份,以便測試您的控制器是否接受有效的身份驗證。只是要確定:測試未經授權的請求導致您現在有重定向的情況。 –

回答

3
thanks, good idea! is there an easy way to mock the auth? – Ron 

我張貼此作爲一個答案,因爲它過多地壓進評論。是的,有一種簡單的方法來模擬AuthenticationService類。首先,查看Stubs/Mocks上的文檔。

您需要做的是從Zend \ Authentication \ AuthenticationService創建模擬並將其配置爲假裝包含身份。

public function testSomethingThatRequiresAuth() 
{ 
    $authMock = $this->getMock('Zend\Authentication\AuthenticationService'); 
    $authMock->expects($this->any()) 
      ->method('hasIdentity') 
      ->will($this->returnValue(true)); 

    $authMock->expects($this->any()) 
      ->method('getIdentity') 
      ->will($this->returnValue($identityMock)); 

    // Assign $authMock to the part where Authentication is required. 
} 

在這個例子中,變量$identityMock需要先前定義。它可能是你的用戶模型類的模擬或類似的東西。

請注意,我沒有測試過它,所以它可能無法立即工作。然而,它只是爲了告訴你方向。

+0

抱歉,這個愚蠢的問題,但如何創建'$ authMock'和我的函數調用之間的連接?一個例子會很棒! – Ron

+2

@不要愚蠢的問題。如果使用serviceLocator來獲取AuthenticationService,請參閱http://www.afewmorelines.com/mocking-user-identities-in-zf2-action-controller-unit-tests/。 – imel96