2014-07-25 45 views
0

我是Zend Framework 2和phpunit測試的新手。首先,我這裏也有類似的問題:Simple ZF2 Unit Tests for a controller using ZfcUser,但是這導致了新的問題,我試圖解決:Zend 2 dispatch在使用phpunit測試時拋出無效參數異常

1) ApplicationControllerTest::testMyActionCanBeAccessed 
Zend\Http\Exception\InvalidArgumentException: A field name was provided without 
a field value 

這裏是我的測試代碼:

class ApplicationControllerTest extends AbstractControllerTestCase 
{ 
protected $controller; 
protected $request; 
protected $response; 
protected $routeMatch; 
protected $event; 
protected $mockedAuthenticationService; 

public function setUp() 
{ 
     $serviceManager = Bootstrap::getServiceManager(); 
     $this->controller = new ApplicationController(); 
     $this->request = new Request(); 
     $this->routeMatch = new RouteMatch(array 
     ('application' => Application\Controller\Application')); 
     $this->event  = new MvcEvent(); 
     $config = $serviceManager->get('Config'); 

     $this->event->setRouteMatch($this->routeMatch); 
     $this->controller->setEvent($this->event); 
     $this->controller->setServiceLocator($serviceManager); 
     $mockAuth = $this->getMock('ZfcUser\Entity\UserInterface'); 

     $ZfcUserMock = $this->getMock('ZfcUser\Entity\User'); 

     $ZfcUserMock->expects($this->any()) 
        ->method('getId') 
        ->will($this->returnValue('1')); 

     $authMock = $this->getMock('ZfcUser\Controller\Plugin\ZfcUserAuthentication'); 

     $authMock->expects($this->any()) 
       ->method('hasIdentity') 
       -> will($this->returnValue(true)); 

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

     $this->controller->getPluginManager() 
     ->setService('zfcUserAuthentication', $authMock); 

     $this->setApplicationConfig(
     include '/path/to/my/testing.php'); 

     parent::setUp(); 

} 

public function testMyActionCanBeAccessed(){ 

    $this->routeMatch->setParam('action', 'my'); 
    $result = $this->controller->dispatch($this->request); 
    $this->assertResponseStatusCode(200); 
    $this->assertModuleName('MyModule'); 
    $this->assertControllerName('mymodule/application'); 
    $this->assertControllerClass('ApplicationController'); 
    $this->assertActionName('My'); 
    $this->assertMatchedRouteName('My'); 

堆棧跟蹤指向行「$結果= $ this-> controller-> dispatch($ this-> request);「所以調度似乎有問題,但是什麼?我有另一個測試工作正常的同一行。

回答

0

AbstractControllerTestCase有一個方法dispatch負責設置各種事情。

嘗試用 $this->dispatch('/url-to-use')

希望它可以幫助交換$result = $this->controller->dispatch($this->request); ...

+0

它幫助,非常感謝你! :) –

相關問題