Laravel Mock Request function only and header


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)
        app()->instance('request', $requestMock->getMock());


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?

Source: Laravel

Categorised as laravel, mocking, php, phpunit, unit-testing Tagged , , , ,


Leave a Reply

Still Have Questions?

Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us