I'm testing an endpoint in my Laravel app. However, I have a middleware that does complex logic to determine the location of the user (using ip reverse look up etc such as this code:
public function getOpCityByIP()
{
// Get the client's remote ip address
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
$clientIpAddress = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
} else {
$clientIpAddress = $_SERVER['REMOTE_ADDR'];
}
$opCityArray = OpCityIP::get($clientIpAddress);
return $opCityArray;
}
I'm not interested in going inside the guts of such methods in said middleware and having to mock them etc. I'd rather simply skip the entire middleware during the unit testing, or at least mock its entire operations and instead hardcode the result to something predetermined. How do I do that?
I'm using Laravel 5.4
i need it to ignore a specific middleware, not all of them
You can use the withoutMiddleware()
method on your test object. As of Laravel 5.5, this method accepts a parameter that lets you specify which middleware to disable, instead of just disabling them all.
In your test:
$this->withoutMiddleware([YourGeoIpMiddleware::class]);