This site uses cookies to deliver our services and to show you relevant ads and job listings.
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
Your use of Stack Overflow’s Products and Services, including the Stack Overflow Network, is subject to these policies and terms.

Join us in building a kind, collaborative learning community via our updated
Code of Conduct.

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
}

2 Answers
2

I know I'm a bit late and I hope you are not waiting for the answer still, but I just had the same problem and hopefully it will still help some people overcome this particular issue. See my solution below:

You can mock the repository class and load it into the IoC container. So when Laravel gets to your controller, it will find it already in there and will resolve your mock instead of instantiating a new one.