vendredi 4 mars 2016

Mocking GeocoderLaravel

I'm using GeocoderLaravel to handle looking up locations via the Google Maps API in a Laravel app. I want to be able to mock the facade so that in tests it doesn't actually query the Google Maps API, so I'm injecting it into the controller, but doing so breaks the controller. Here's the relevant parts of the controller:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Location;
use Geocoder;

class LocationController extends Controller
{
    protected $geocoder;

    public function __construct(Geocoder $geocoder)
    { 
        $this->geocoder = $geocoder;
    } 

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    { 
        // Get location
        $location = $request->input('location');

        try { 
            // Look up location
            $result = $this->geocoder->geocode($location);

            // Return response
            return response()->json($result->toArray(), 200);
        } catch (\Exception $e) { 
            $data = [ 
                'message' => $e->getMessage()
            ];
            return response()->json($data, 400);
        }
    }
}

I get the following error when I run the tests or try to make a request to this method:

PHP Fatal error:  Call to undefined method Toin0u\Geocoder\Facade\Geocoder::geocode()

Using PsySh to insert a breakpoint just before that's called, it does indeed look like the geocode() method is defined, but I'm not sure why. Can anyone explain where I've gone wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire