Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Mock RequestStack of symfony

I don't understand how mock this : $requestStack->getCurrentRequest()->getContent()

there are 2 methods : getCurrentRequest()->getContent() and it return a json object (POST Response)

I use symfony with RequestStack class.

The entire code is

class MessageReceivedService
{
    protected $message;

    public function __construct(RequestStack $requestStack)
    {
        $this->message = json_decode($requestStack->getCurrentRequest()->getContent());
    }

    public function getMessage()
    {
        return $this->message;
    }
}
like image 877
timothy L Avatar asked Dec 19 '22 17:12

timothy L


1 Answers

You don't actually have to mock the RequestStack class, since it's basically a container.

If you want to test with the RequestStack, you could do something like this:

<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class MessageReceivedServiceTest extends \PHPUnit_Framework_TestCase
{
    public function test()
    {
        $request = new Request([], [], [], [], [], [], [], json_encode([
            'foo' => 'bar'
        ]));

        $requestStack = new RequestStack();
        $requestStack->push($request);

        // Do your tests
    }
}

When you call currentRequest on the $requestStack variable, it should return the $request variable.

like image 51
Ramon Kleiss Avatar answered Jan 14 '23 03:01

Ramon Kleiss