0

I have an API built in Symfony using the FOSRestBundle.

I want to write a simple test to validate whether when I submit some JSON that the results get properly processed and the expected response gets returned.

Working test code

$user = $this->getResourceContent('userValid.json');
$this->client->request('POST', '/users', json_decode($user, true), [], $this->headers);

I can get the request to successfully submit by providing the 'user' as form POST values. However this is not the behavior that I am trying to test.

Failing test case

$user = $this->getResourceContent('userValid.json');
$this->client->request('POST', '/users', [], [], $this->headers, $user);

This is what I want to test providing the JSON as the request body so that it can be processed. However this does not work since the $form->isValid() check fails since the form has not been submitted.

Controller action

public function postUserAction(Request $request)
{
    $user = new User();
    $form = $this->createForm(new UserType(), $user, ['method' => 'POST']);
    $form->handleRequest($request);

    if ($form->isValid()) {

        // TODO: Persist user

        $view = $this->jsendView(['user' => $user], 201, Jsend::SUCCESS);
        $view->getSerializationContext()->setGroups(['Default', 'private']);
        return $view;
    }

    return $form;
}
Malachi
  • 33,142
  • 18
  • 63
  • 96
  • 1
    Did you add code to your form (or anywhere for that matter) to allow you to parse a JSON request body? Seems like that key piece is missing. If you want to use the form then you need to add some logic to your `handleRequest` method on the form, if you want it all handled in the controller or by some Service or Model then you need to create those and use them appropriately then the request body is JSON. – prodigitalson Jan 09 '15 at 14:56
  • 1
    Ahhh The `FOSRestBundle` has a `BodyListener` to decode the request content into the parameterbag to be processed as if it was a form. Thanks for the heads up. I'll look into this further and see if I can hook this aspect up into the test. I assumed that calling `$client->request` would be the same as if I was making a call with the application. – Malachi Jan 09 '15 at 15:10

0 Answers0