Skip to content

Instantly share code, notes, and snippets.

@Snaver
Created May 19, 2020 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Snaver/05db2d2f8025b4d60e498edd68deec05 to your computer and use it in GitHub Desktop.
Save Snaver/05db2d2f8025b4d60e498edd68deec05 to your computer and use it in GitHub Desktop.
geocoder-php / GeocoderLaravel Testing and Mocking Setup
<?php
namespace App;
use Geocoder\Laravel\ProviderAndDumperAggregator as G;
class Geocoder
{
protected $geocoder;
public function __construct(G $geocoder)
{
$this->geocoder = $geocoder;
}
public function geocode($search)
{
return $this->geocoder->geocode(trim($search))->get();
}
}
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Geocoder;
class ExampleController extends Controller
{
/**
*
* @return Response
*/
public function __invoke(Request $request, Geocoder $geocoder)
{
//...
$geocode = $geocoder->geocode($request->location);
$geocode->first()->getCoordinates()->getLatitude();
$geocode->first()->getCoordinates()->getLongitude();
if (method_exists($geocode->first(), 'getFormattedAddress')) {
$resolved_location = $geocode->first()->getFormattedAddress();
}
// ...
}
}
<?php
namespace Tests\Feature\Api;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Geocoder\Laravel\ProviderAndDumperAggregator as G;
class VenueSearchTest extends TestCase
{
use RefreshDatabase;
/**
* Venue location search endpoint
*
* @return void
*/
public function testVenueLocationSearch()
{
// Use the fake implementation
$this->app->bind(\App\Geocoder::class, function () {
return new \Tests\Mocks\Geocoder(new G());
});
// Hit the endpoint..
$query = http_build_query([
'location' => 'norwich',
]);
$response = $this->getJson('/api/venue-search?' . $query);
$response
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonStructure([
'data' => [],
'links' => [],
'meta' => [],
]);
}
}
<?php
namespace Tests\Mocks;
use Geocoder\Model\Address;
use Geocoder\Model\AddressCollection;
class Geocoder extends \App\Geocoder
{
public function geocode($search)
{
return new AddressCollection([
Address::createFromArray([
'providedBy' => 'mock',
'latitude' => '52.6308859',
'longitude' => '1.297355',
'locality' => 'Norwich',
'postalCode' => null,
'adminLevels' => [],
'countryCode' => 'GB',
]),
]);
return collect([]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment