我正在尝试使用 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 对象来做到这一点呢?