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.
Advertisement
Answer
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.