Mocking interface dependency of controllers in Laravel testing












2














I'm just trying to test my Laravel app. When coding the project, I was trying to take care about "fat services, skinny controllers" principle, so every logic (including DB logic) is extracted to service classes with interfaces, and injected into the controllers. Then, the dependencies are resolved by IoC container provided by Laravel.



My question is regarding to mocking out these interface dependencies when testing the controllers. To me, it seems like the dependency injection is never properly resolved by the test, it is always using the implementation which is injected by the IoC Container, and not the fake one.



Example Controller Method



public function index(ICrudService $crudService)
{
if (!Auth::check()) {
return redirect()->route('login');
}
$comps = $crudService->GetAllCompetitions();

return view('competitions.index', ['competitions' => $comps]);
}


setUp method



protected function setUp()
{
parent::setUp();
$this->faker = FakerFactory::create();

// Create the mock objects
$this->user = Mockery::mock(User::class);
$this->allComps = new Collection();
for ($i=0; $i<10; $i++)
{
$this->allComps->add(new Competition(['comp_id' => ++$i,
'comp_name' => $this->faker->unique()->company,
'comp_date' => "2018-11-07 17:25:41"]));

}

$this->user->shouldReceive('getAuthIdentifier')
->andReturn(1);

$this->competitionFake = Mockery::mock(Competition::class);

// Resolve every Competition params with this fake
$this->app->instance(Competition::class, $this->competitionFake);
}


The test



public function test_competition_index()
{
// Mock the Crud Service.
$fakeCrud = Mockery::mock(ICrudService::class);

// Register the fake Crud Service to DI container.
$this->app->instance(ICrudService::class, $fakeCrud);

// Mock GetALllCompetitions method to return the fake collection.
$fakeCrud->shouldReceive('GetAllCompetitions')
->once()
->andReturn
($this->allComps);

// Authenticate the mock user.
$this->be($this->user);

// Send the request to the route, and assert if the view has competitions array.
$this->actingAs($this->user)->get('competitions')->assertStatus(200);
}


CrudServiceProvider



    /**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('AppServicesInterfacesICrudService', function () {
return new CommonCrudService();
});
}

/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['AppServicesInterfacesICrudService'];
}


The behaviour



The test fails because of HTTP response 500 instead of 200. When debugging, I could see that the controller is still using the CommonCrudService class provided by the ServiceProvider, and not the fake one. If I comment out the CrudServiceProvider, the fake service is being passed to the controller, and returns the collection that I specified. Of course, I want to keep the container for my application.



Had anyone experienced things like this?



Thanks a lot in advance!










share|improve this question






















  • so why are mocking Competion class instead of ICrudService?
    – Fatemeh Majd
    Dec 2 '18 at 11:52
















2














I'm just trying to test my Laravel app. When coding the project, I was trying to take care about "fat services, skinny controllers" principle, so every logic (including DB logic) is extracted to service classes with interfaces, and injected into the controllers. Then, the dependencies are resolved by IoC container provided by Laravel.



My question is regarding to mocking out these interface dependencies when testing the controllers. To me, it seems like the dependency injection is never properly resolved by the test, it is always using the implementation which is injected by the IoC Container, and not the fake one.



Example Controller Method



public function index(ICrudService $crudService)
{
if (!Auth::check()) {
return redirect()->route('login');
}
$comps = $crudService->GetAllCompetitions();

return view('competitions.index', ['competitions' => $comps]);
}


setUp method



protected function setUp()
{
parent::setUp();
$this->faker = FakerFactory::create();

// Create the mock objects
$this->user = Mockery::mock(User::class);
$this->allComps = new Collection();
for ($i=0; $i<10; $i++)
{
$this->allComps->add(new Competition(['comp_id' => ++$i,
'comp_name' => $this->faker->unique()->company,
'comp_date' => "2018-11-07 17:25:41"]));

}

$this->user->shouldReceive('getAuthIdentifier')
->andReturn(1);

$this->competitionFake = Mockery::mock(Competition::class);

// Resolve every Competition params with this fake
$this->app->instance(Competition::class, $this->competitionFake);
}


The test



public function test_competition_index()
{
// Mock the Crud Service.
$fakeCrud = Mockery::mock(ICrudService::class);

// Register the fake Crud Service to DI container.
$this->app->instance(ICrudService::class, $fakeCrud);

// Mock GetALllCompetitions method to return the fake collection.
$fakeCrud->shouldReceive('GetAllCompetitions')
->once()
->andReturn
($this->allComps);

// Authenticate the mock user.
$this->be($this->user);

// Send the request to the route, and assert if the view has competitions array.
$this->actingAs($this->user)->get('competitions')->assertStatus(200);
}


CrudServiceProvider



    /**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('AppServicesInterfacesICrudService', function () {
return new CommonCrudService();
});
}

/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['AppServicesInterfacesICrudService'];
}


The behaviour



The test fails because of HTTP response 500 instead of 200. When debugging, I could see that the controller is still using the CommonCrudService class provided by the ServiceProvider, and not the fake one. If I comment out the CrudServiceProvider, the fake service is being passed to the controller, and returns the collection that I specified. Of course, I want to keep the container for my application.



Had anyone experienced things like this?



Thanks a lot in advance!










share|improve this question






















  • so why are mocking Competion class instead of ICrudService?
    – Fatemeh Majd
    Dec 2 '18 at 11:52














2












2








2







I'm just trying to test my Laravel app. When coding the project, I was trying to take care about "fat services, skinny controllers" principle, so every logic (including DB logic) is extracted to service classes with interfaces, and injected into the controllers. Then, the dependencies are resolved by IoC container provided by Laravel.



My question is regarding to mocking out these interface dependencies when testing the controllers. To me, it seems like the dependency injection is never properly resolved by the test, it is always using the implementation which is injected by the IoC Container, and not the fake one.



Example Controller Method



public function index(ICrudService $crudService)
{
if (!Auth::check()) {
return redirect()->route('login');
}
$comps = $crudService->GetAllCompetitions();

return view('competitions.index', ['competitions' => $comps]);
}


setUp method



protected function setUp()
{
parent::setUp();
$this->faker = FakerFactory::create();

// Create the mock objects
$this->user = Mockery::mock(User::class);
$this->allComps = new Collection();
for ($i=0; $i<10; $i++)
{
$this->allComps->add(new Competition(['comp_id' => ++$i,
'comp_name' => $this->faker->unique()->company,
'comp_date' => "2018-11-07 17:25:41"]));

}

$this->user->shouldReceive('getAuthIdentifier')
->andReturn(1);

$this->competitionFake = Mockery::mock(Competition::class);

// Resolve every Competition params with this fake
$this->app->instance(Competition::class, $this->competitionFake);
}


The test



public function test_competition_index()
{
// Mock the Crud Service.
$fakeCrud = Mockery::mock(ICrudService::class);

// Register the fake Crud Service to DI container.
$this->app->instance(ICrudService::class, $fakeCrud);

// Mock GetALllCompetitions method to return the fake collection.
$fakeCrud->shouldReceive('GetAllCompetitions')
->once()
->andReturn
($this->allComps);

// Authenticate the mock user.
$this->be($this->user);

// Send the request to the route, and assert if the view has competitions array.
$this->actingAs($this->user)->get('competitions')->assertStatus(200);
}


CrudServiceProvider



    /**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('AppServicesInterfacesICrudService', function () {
return new CommonCrudService();
});
}

/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['AppServicesInterfacesICrudService'];
}


The behaviour



The test fails because of HTTP response 500 instead of 200. When debugging, I could see that the controller is still using the CommonCrudService class provided by the ServiceProvider, and not the fake one. If I comment out the CrudServiceProvider, the fake service is being passed to the controller, and returns the collection that I specified. Of course, I want to keep the container for my application.



Had anyone experienced things like this?



Thanks a lot in advance!










share|improve this question













I'm just trying to test my Laravel app. When coding the project, I was trying to take care about "fat services, skinny controllers" principle, so every logic (including DB logic) is extracted to service classes with interfaces, and injected into the controllers. Then, the dependencies are resolved by IoC container provided by Laravel.



My question is regarding to mocking out these interface dependencies when testing the controllers. To me, it seems like the dependency injection is never properly resolved by the test, it is always using the implementation which is injected by the IoC Container, and not the fake one.



Example Controller Method



public function index(ICrudService $crudService)
{
if (!Auth::check()) {
return redirect()->route('login');
}
$comps = $crudService->GetAllCompetitions();

return view('competitions.index', ['competitions' => $comps]);
}


setUp method



protected function setUp()
{
parent::setUp();
$this->faker = FakerFactory::create();

// Create the mock objects
$this->user = Mockery::mock(User::class);
$this->allComps = new Collection();
for ($i=0; $i<10; $i++)
{
$this->allComps->add(new Competition(['comp_id' => ++$i,
'comp_name' => $this->faker->unique()->company,
'comp_date' => "2018-11-07 17:25:41"]));

}

$this->user->shouldReceive('getAuthIdentifier')
->andReturn(1);

$this->competitionFake = Mockery::mock(Competition::class);

// Resolve every Competition params with this fake
$this->app->instance(Competition::class, $this->competitionFake);
}


The test



public function test_competition_index()
{
// Mock the Crud Service.
$fakeCrud = Mockery::mock(ICrudService::class);

// Register the fake Crud Service to DI container.
$this->app->instance(ICrudService::class, $fakeCrud);

// Mock GetALllCompetitions method to return the fake collection.
$fakeCrud->shouldReceive('GetAllCompetitions')
->once()
->andReturn
($this->allComps);

// Authenticate the mock user.
$this->be($this->user);

// Send the request to the route, and assert if the view has competitions array.
$this->actingAs($this->user)->get('competitions')->assertStatus(200);
}


CrudServiceProvider



    /**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('AppServicesInterfacesICrudService', function () {
return new CommonCrudService();
});
}

/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['AppServicesInterfacesICrudService'];
}


The behaviour



The test fails because of HTTP response 500 instead of 200. When debugging, I could see that the controller is still using the CommonCrudService class provided by the ServiceProvider, and not the fake one. If I comment out the CrudServiceProvider, the fake service is being passed to the controller, and returns the collection that I specified. Of course, I want to keep the container for my application.



Had anyone experienced things like this?



Thanks a lot in advance!







php laravel testing dependency-injection phpunit






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 11:44









Kristóf Siket

111




111












  • so why are mocking Competion class instead of ICrudService?
    – Fatemeh Majd
    Dec 2 '18 at 11:52


















  • so why are mocking Competion class instead of ICrudService?
    – Fatemeh Majd
    Dec 2 '18 at 11:52
















so why are mocking Competion class instead of ICrudService?
– Fatemeh Majd
Dec 2 '18 at 11:52




so why are mocking Competion class instead of ICrudService?
– Fatemeh Majd
Dec 2 '18 at 11:52

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53411327%2fmocking-interface-dependency-of-controllers-in-laravel-testing%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53411327%2fmocking-interface-dependency-of-controllers-in-laravel-testing%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'