简体   繁体   中英

How to mock properly Illuminate\Http\Request class from Laravel

I'm trying to test a method from a class which contains a method using the request() helper from Laravel. This is the method:

Category class

public function getCanonicalUrl()
{
    return preg_match('/\/sale\/./', request()->getRequestUri())
         ? ''
         : url($this->getUrlKey());
}

The test should make this helper to catch properly the URI when doing getRequestUri() but it's actually returning an empty string. This is one of the thousand tries that I gave to the test.

Test

public function testCanonical()
{
    // ...

    $requestMock = Mockery::mock(Request::class)
      ->shouldReceive('getRequestUri')
      ->andReturn('/sale/random-string');

    $this->app->instance(Request::class, $requestMock);

    // ...
}

Any ideas of how this could be achieved? Thanks in advance.

You should not mock the Request facade. Instead, pass the input you desire into the HTTP helper methods such as get and post when running your test.

https://laravel.com/docs/5.5/mocking#mocking-facades

Per https://stackoverflow.com/a/61903688/135114 , if

  1. your function under test takes a $request argument, and
  2. you don't need to do funky stuff to the Request—real route paths are good enough for you

... then you don't need to "mock" a Request (as in, mockery),
you can just create a Request and pass it, eg

public function test_myFunc_condition_expectedResult() {
    ...
    $mockRequest = Request::create('/path/that/I_want', 'GET'); 
    $this->assertTrue($myClass->myFuncThat($mockRequest));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM