Chris Mitchell
Chris Mitchell

Reputation: 904

Using Zend Framework 2 how to attach parameters to a request object when using put method?

I'm trying to test a REST update method using phpunit. I create a request object, match a route, and dispatch it to the controller:

$this->routeMatch->setParam('id', '1');
$this->request->setMethod(Request::METHOD_PUT);
$result = $this->controller->dispatch($this->request);

All working fine, but the problem I'm having is how do I pass data with this request? I've tried attaching via post or get method, but no luck:

$this->request->getQuery()->set('description', 'foo'); //Nope
$this->request->getPost()->set('description', 'foo'); //Nope

I'm not seeing a ->getPut() method... How can I add data to a request object that uses put method? I am not seeing any parameters come through in my controller, except the matched route id.

Update:

//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);

Update 2 This works:

$ curl -i -H "Accept: application/json" -X PUT -d "title=something&description=something else" http://mysite.com

So how to do that with a Zend\Http\Request object?

Upvotes: 0

Views: 3242

Answers (2)

perl2012
perl2012

Reputation: 149

Make sure you also set Content-type to application/json. I got hung up on that for hours:

How do I send a PUT request in ZendFramework2?

Upvotes: 1

Crisp
Crisp

Reputation: 11447

Not overly familiar with the RESTful stuff in zf2, but I think for PUT it reads the request body, so you should use setContent()

$this->request->setMethod(Request::METHOD_PUT)
              ->setContent("title=something&description=something else");

Upvotes: 1

Related Questions