2014-04-22 46 views
2

我在Zend Framework 2應用程序中測試AbstractRestfulController。ZF2中AbstractRestfulController的PHPUnit測試設置

我沒有連基本的斷言

我在想,我的設置有可能被打破..即不匹配的路線正確。我如何在控制器中打印出來,以確保我在ZF2RestServiceTest.setup()中的設置是正確的?

文檔是什麼飛到哪裏,這裏非常稀少:

ControllerTest.php

protected function setUp() 
{ 
    $serviceManager = Bootstrap::getServiceManager(); 
    $this->controller = new IndexController(); 
    $this->request = new Request(); 
    $this->routeMatch = new RouteMatch(array('controller' => 'IndexController')); 
    $this->event  = new MvcEvent(); 

    $config = $serviceManager->get('Config'); 
    $routerConfig = isset($config['router']) ? $config['router'] : array(); 

    $router = HttpRouter::factory($routerConfig); 
    $this->event->setRouter($router); 
    $this->event->setRouteMatch($this->routeMatch); 
    $this->controller->setEvent($this->event); 
    $this->controller->setServiceLocator($serviceManager); 
} 

RouteMatch發生在一個數組,尋找在module.config.php設置我的控制器的名字嗎?

public function testIndexActionCanBeAccessed() 
{ 
    $this->routeMatch->setParam('action', 'index'); 

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

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

module.config.php

<?php 

return array(
    'router' => array(
     'routes' => array(
      'myservice' => array(
       'type' => 'Zend\Mvc\Router\Http\Segment', 
       'options' => array(
        'route' => '/api/myservice[/:optionalParameter]', 
        'constraints' => array(
         'id' => '\w+' 
        ), 
        'defaults' => array(
         'controller' => 'MyService\Controller\Index' 
        ), 
       ), 
      ), 
     ), 
    ), 
    'controllers' => array(
     'invokables' => array(
      'MyService\Controller\Index' => 'MyService\Controller\IndexController', 
     ), 
    ), 
); 

測試結果

PHPUnit_Framework_ExpectationFailedException : Failed asserting that 404 matches expected 200. 
Expected :200 
Actual :404 

回答

1

事實證明,我需要這部分下足控制器名稱,並修改HTTP參數因爲我沒有使用動作控制器。

什麼困惑我是一個很大的Zend框架的代碼示例使用別名,或不同的控制器類型..

這裏,幫助鏈接:https://github.com/RichardKnop/zend-v2-skeleton

protected function setUp() 
{ 
    $serviceManager = Bootstrap::getServiceManager(); 
    $this->controller = new IndexController(); 
    $this->request = new Request(); 
    $this->routeMatch = new RouteMatch(array('controller' => 'MyService\Controller\Index')); 
    $this->event  = new MvcEvent(); 

... 

public function testIndexActionCanBeAccessed() 
{ 
    $this->routeMatch->setParam('optionalParameter', 'someParam'); 

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

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