-1

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?

Nele
  • 83
  • 1
  • 13
  • 1
    you could also create a Request instance yourself and fill it as needed with inputs and headers as you like and bind that – lagbox Jan 14 '22 at 14:25
  • 1
    you don't have to mock a `request`... Please, read [my answer](https://stackoverflow.com/questions/69150653/how-to-feature-test-more-complicated-cases-on-laravel-using-phpunit/69155061#69155061) as it is related to this. – matiaslauriti Jan 14 '22 at 21:13
  • thanks for your help. I found a solution now. :) – Nele Jan 17 '22 at 09:26

1 Answers1

1

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);
Nele
  • 83
  • 1
  • 13