这是针对ZF2控制器的post DATA实现的PHPUnit测试:
public function testEditActionPost()
{
$this->routeMatch->setParam('action', 'editaffaire');
$this->routeMatch->setParam('idaffaire', '400');
$data = array(
'foo' => 'bar',
'bar' => 'foo'
);
$this->request->setMethod('POST')
->setPost($data);
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
但这不起作用...... PHPUnit向我发送错误:
1)MaintenanceTest \ Controller \ SitesControllerTest :: testEditActionPost 传递给Zend \ Http \ Request :: setPost()的参数1必须是一个实例 Zend \ St dlib \ ParametersInterface,给定数组
这是我的setUp:
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new SitesController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$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);
}
如何发送测试控制器?谢谢!
编辑 - 控制器代码:
public function editaffaireAction()
{
try {
$iMaiAffaireId = $this->params('idaffaire');
$oAffaire = $this->maiAffaireService->selectByIdOrCreate($iMaiAffaireId);
$maiAffairesForm = new FMaiAffaireForm(
$oAffaire
);
if ($this->getRequest()->isPost()) {
$maiAffairesForm->setInputFilter($oAffaire->getInputFilter());
$postData = $this->getRequest()->getPost();
$maiAffairesForm->setData($postData);
if ($maiAffairesForm->isValid()) {
$aData = $maiAffairesForm->getData();
$oAffaire->exchangeArray($aData);
$iMaiAffaireId = $this->maiAffaireService->save($oAffaire);
}
}
$viewModel = new ViewModel([
'oAffaire' => $oAffaire
]);
return $viewModel;
} catch (\Exception $e) {
throw new \Exception($e);
}
}
答案 0 :(得分:2)
您要传递给setPost()
的参数需要位于Parameters
对象中:
use Zend\Stdlib\Parameters;
//...
$this->request->setMethod('POST')
->setPost(new Parameters($data));
请参阅Zend 2的文档: http://framework.zend.com/manual/current/en/modules/zend.test.phpunit.html#testing-your-controllers-and-mvc-applications