0

I have the class that returns values from HttpFoundation request object. I want to write tests for that class and I have problem. That is my class:

class RequestCollected 
{
    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function getUserAgent(): string
    {
        return $this->request->headers->get('User-Agent');
    }

    public function getUri(): string
    {
        return $this->request->request->get('uri');
    }
}

And that are my tests:

public function testGetUserAgent()
    {
        $userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';
        $request = $this->prophesize(Request::class);
        $request->headers = $this->prophesize(HeaderBag::class);
        $request->headers->get('User-Agent')->willReturn($userAgent);

        $collected = new RequestCollected($request->reveal());

        $this->assertEquals($userAgent, $collected->getUserAgent());
    }

    public function testGetUri()
    {
        $uri = 'test';
        $request = $this->prophesize(Request::class);
        $request->request = $this->prophesize(ParameterBag::class);
        $request->request->get('uri')->willReturn($uri);

        $collected = new RequestCollected($request->reveal());

        $this->assertEquals($uri, $collected->getUri());
    }

Error is same for both tests: Error: Call to a member function willReturn() on null

There is any solution for that? Or another method to test something what is using request object?

Greetings

2
  • Why are you doing $request->request->headers instead of $request->headers? Commented May 4, 2017 at 14:16
  • My bad. Now error is "Error: Call to a member function willReturn() on null" like in second test Commented May 4, 2017 at 14:23

1 Answer 1

1

You don't need use prophesy or mock object to test this simple class

public function testGetUserAgent()
{
    $userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';
    $request = new Request();
    $request->headers = new HeaderBag(['User-Agent' => $userAgent]);
    $collected = new RequestCollected($request);
    $this->assertEquals($userAgent, $collected->getUserAgent());
}

The only that you need is check if your class is getting the information for a valid request, sometimes things are simpler than we think :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.