Monday, February 21, 2022

[FIXED] Laravel Mock Request function only and header

Issue

I test code with PHPUnit 9.0. I use Laravel framework 8.* and PHP 7.4

I struggle to test a function that uses request()

Here is a very short version of the code I have to test:

trait SomeTrait
{

  function someFunction()
  {
     //1. retrieve only the documents
     $documents = request()->only('documents');

     ....

     //set an array called $header
     $header = [ 'Accept-Encoding' => 'application/json'];

     //2. add to Array $header if someKey is available in headers
     if (request()->headers->has('someKey'))
     {
       $header = Arr::add($header, 'someKey', request()->header('someKey'));
     }
   }
}

At first (1.) it has to get the documents from a request. I solved this with an mock of the request and it works:


$requestMock = Mockery::mock(Request::class)
            ->makePartial()
            ->shouldReceive('only')
            ->with('documents')
            ->andReturn($document_data);
        app()->instance('request', $requestMock->getMock());

$this->someFunction();

I create a mock of request class, that returns $document_data when request()->only('documents'); is called in someFunction().

But then the code request()->headers->has('someKey') returns the error: Call to a member function has() on null

Can anybody help and explain how I can test the code?


Solution

Thanks for the help! I found a solution without mocking the request - sometimes it's easier than you think :D

//create a request 
$request = new Request();

//replace the empty request with an array
$request->replace(['documents' => $all_documents]);

//replace the empty request header with an array
$request->headers->replace(['someKey' => 'someValue']);

//bind the request
app()->instance('request', $request);


Answered By - Nele

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.