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.
Per https://stackoverflow.com/a/61903688/135114 , if
$request
argument, and... 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.