timothy L
timothy L

Reputation: 85

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

Upvotes: 7

Views: 5371

Answers (1)

Ramon Kleiss
Ramon Kleiss

Reputation: 1749

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.

Upvotes: 22

Related Questions