jeudi 25 février 2016

Laravel unit test route model binding

In my RouteServiceProvider.php i have:

public function boot(Router $router)
{
    parent::boot($router);

    $router->model('fileId', 'App\File');
}

In my FileController.php i have:

public function destroy(\App\File $file)
{
    $error = $this->fileService->delete($file);

    if (is_null($error)) {
        return $this->respondOk(null, 'Successfully deleted.');
    }

    return $this->respondError($error);
}

The question is how to write an unit test for this scenario. I am struggling with mocking this binded model with no success. For now i have:

class FileControllerTest extends \App\TestCase {

    public function __construct()
    {
        $this->fileService  = m::mock('App\Services\File');
        $this->fileModel    = m::mock('App\File');
    }

    public function testCatchExceptionWhileDeleting()
    {
        $file = new \App\File([
            'id'    => $this->faker->randomDigitNotNull,
            'name'  => $this->faker->text(30)
        ]);

        $error = $this->faker->text();

        $this->fileModel
            ->shouldReceive('first')
            ->once()
            ->andReturn($file);

        $this->fileService
            ->shouldReceive('delete')
            ->once()
            ->andReturn($error);

        $this->app->instance('App\Services\File', $this->fileService);
        $this->app->instance('App\File', $this->fileModel);

        $response = $this->call('DELETE', sprintf('/admin/files/%s', $file->id));

    }
}

Aucun commentaire:

Enregistrer un commentaire