Php 在ZF2控制器测试中断言POST数据
以下是针对ZF2控制器实施post数据的PHPUnit测试:Php 在ZF2控制器测试中断言POST数据,php,zend-framework2,phpunit,Php,Zend Framework2,Phpunit,以下是针对ZF2控制器实施post数据的PHPUnit测试: public function testEditActionPost() { $this->routeMatch->setParam('action', 'editaffaire'); $this->routeMatch->setParam('idaffaire', '400'); $data = array( 'foo' =&g
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\Parameters接口的名称,给定数组
以下是我的设置:
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);
}
}
要传递给
setPost()
的参数需要位于parameters
对象中:
use Zend\Stdlib\Parameters;
//...
$this->request->setMethod('POST')
->setPost(new Parameters($data));
请参阅Zend 2的文档:
它可以工作,但我的表单无效,它显示“不在数组中”错误,为什么?我真的不在命令下。。。我的值在我的数组中,并在我的请求中发送!既然我不知道你的控制器代码,我就不能帮你解决这个问题:-)好的,我明白了。我的元素是选择输入。如果我将样本数据作为测试发送,这会向我发送一个错误“在干草堆中找不到输入”,我在我的选择中用“disable\u inarray\u validator”=>true来更正它。。。