Jeffrey L. Roberts
Jeffrey L. Roberts

Reputation: 2994

Symfony 3.4 - How to mock Request object for PHPUnit Test of Service

I have a service that I need to write a phpunit test for

This service has a method that accepts a Symfony\Component\HttpFoundation\Request object that comes from a JSON POST

I need to somehow mock the Request object with a JSON POST so that I can test this method properly

Here is what the Service method looks like

namespace AppBundle\Service;

use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class SubscriptionNotificationProcessor
 * @package AppBundle\Service
 */
class SubscriptionNotificationProcessor
{
     ...
     public function process(Request $request)
     {
           $parameterBag = $request->request;
           $notification_type = $parameterBag->get('notification_type');
           ...
      }
 }

My question is, How do I mock the Request parameter populated with JSON data?

Upvotes: 1

Views: 3114

Answers (1)

isom
isom

Reputation: 304

This is the constructor of Symfony\Component\HttpFoundation\Request

public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
    {
        $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
    }

As you can see the $resquest is the second parameter, you could do something like this:

$request = new Request([], [json_encode([ 'foo' => 'bar'])], [], [], [], [], []);

now you can pass the object to your service process($request);

Upvotes: 0

Related Questions