PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] Laravel Mock Request function only and header

 February 20, 2022     laravel, mocking, php, phpunit, unit-testing     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing