jeudi 30 juillet 2015

Laravel mocking controller dependancy

In my Laravel app I have a controller with a method to show a particular resource. E.g. say the url is /widgets/26 My controller method might work like so:

Class WidgetsController {
    protected $widgets;

    public function __construct(WidgetsRepository $widgets)
    {
        $this->widgets = $widgets;
    }

    public function show($id)
    {
        $widget = $this->widgets->find($id);

        return view('widgets.show')->with(compact('widget'));
    }
}

As we can see my WidgetsController has a WidgetsRepository dependency. In a unit test for the show method, how can I mock this dependency so that I don't actually have to call the repository and instead just return a hard-coded widget?

Unit test start:

function test_it_shows_a_single_widget()
{
    // how can I tell the WidgetsController to be instaniated with a mocked WidgetRepository?
    $response = $this->action('GET', 'WidgetsController@show', ['id' => 1]);

    // somehow mock the call to the repository's `find()` method and give a hard-coded return value
    // continue with assertions
}

Aucun commentaire:

Enregistrer un commentaire