php - Mocking Laravel controller dependency -


in laravel app have controller method show particular resource. e.g. url /widgets/26 controller method might work 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 can see widgetscontroller has widgetsrepository dependency. in unit test show method, how can mock dependency don't have call repository , instead return hard-coded widget?

unit test start:

function test_it_shows_a_single_widget() {     // how can tell widgetscontroller instaniated mocked widgetrepository?     $response = $this->action('get', 'widgetscontroller@show', ['id' => 1]);      // somehow mock call repository's `find()` method , give hard-coded return value     // continue assertions } 

i know i'm bit late , hope not waiting answer still, had same problem , still people overcome particular issue. see solution below:

you can mock repository class , load ioc container. when laravel gets controller, find already in there , resolve mock instead of instantiating new one.

function test_it_shows_a_single_widget() {     // mock repository     $repository = mockery::mock(widgetrepository::class);     $repository->shouldreceive('find')         ->with(1)         ->once()         ->andreturn(new widget([]));      // load mock ioc container     $this->app->instance(widgetrepository::class, $repository);      // when making call, controller use mock     $response = $this->action('get', 'widgetscontroller@show', ['id' => 1]);      // continue assertions     // ... } 

a similar setup has been tested , working fine in laravel 5.3.21.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -