mercredi 21 novembre 2018

Mocking interface dependency of controllers in Laravel testing

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 =  Faker\Factory::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('App\Services\Interfaces\ICrudService', function () {
        return new CommonCrudService();
    });
}

/**
 * Get the services provided by the provider.
 *
 * @return array
 */
public function provides()
{
    return ['App\Services\Interfaces\ICrudService'];
}

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!

Aucun commentaire:

Enregistrer un commentaire