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