我正在测试Zend Framework 2应用程序中的AbstractRestfulController。
我甚至连基本断言都失败了
我在想我的设置可能会被破坏..即没有正确匹配路由。如何在控制器中打印出来,以确保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
答案 0 :(得分:1)
事实证明我需要此部分下的完整控制器名称,并修改http参数,因为我没有使用动作控制器。
让我感到困惑的是很多Zend Framework代码示例都在使用别名或不同的Controller类型。
这里有帮助的链接: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());
}