1
votes

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?

1
as I know, you don't need to mocking the Request object, you can create your own request instance and call your serviceisom
How would I get the JSON data into if I just create my own instance?Jeffrey L. Roberts
Why not just mock it? gianarb.it/blog/symfony-unit-test-controller-with-phpunit Just be aware that it's usually not worth unit testing controller actions. You can unit test any custom service the action might use but functional testing it typically the way to go.Cerad

1 Answers

0
votes

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