我正在尝试使用phpunit测试REST更新方法。我创建一个请求对象,匹配路由,并将其分派给控制器:
$this->routeMatch->setParam('id', '1');
$this->request->setMethod(Request::METHOD_PUT);
$result = $this->controller->dispatch($this->request);
一切正常,但我遇到的问题是如何通过此请求传递数据?我试过通过post或get方法附加,但没有运气:
$this->request->getQuery()->set('description', 'foo'); //Nope
$this->request->getPost()->set('description', 'foo'); //Nope
我没有看到 - > getPut()方法...如何将数据添加到使用put方法的请求对象?我没有在控制器中看到任何参数,除了匹配的路由ID。
更新
//Create mocks:
$statusMock=new Status();
$statusMock->exchangeArray($testData);
$statusTableMock = $this->getMockBuilder('Status\Model\StatusTable')
->disableOriginalConstructor()
->getMock();
$statusTableMock->expects($this->any())
->method("getStatus")
->will($this->returnValue($statusMock));
$statusTableMock->expects($this->once())
->method('updateStatus')
->will($this->returnValue(array()));
//pass mocks to service manager, will use mocks instead of actual model
$serviceManager = Bootstrap::getServiceManager();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Status\Model\StatusTable', $statusTableMock);
//set route and request object
$this->routeMatch->setParam('id', '1');
$this->request->setMethod(Request::METHOD_PUT);
//try to attach data
$this->request->getQuery()->set('description', 'foo'); //NOPE!
$this->request->getPost()->set('title', 'bar'); //NOPE!
//Send and test
$result = $this->controller->dispatch($this->request);
$this->assertResponseStatusCode(200);
更新2 这有效:
$ curl -i -H "Accept: application/json" -X PUT -d "title=something&description=something else" http://mysite.com
那么如何使用Zend \ Http \ Request对象?
答案 0 :(得分:1)
对zf2中的RESTful内容不太熟悉,但我认为对于PUT它会读取请求体,所以你应该使用setContent()
$this->request->setMethod(Request::METHOD_PUT)
->setContent("title=something&description=something else");
答案 1 :(得分:1)
确保您还将Content-type设置为application / json。我被挂了好几个小时: