jeudi 28 avril 2016

Laravel 5 : Is it possible to use __construct() and Illuminate\Http\Request for testcase classes?

I'm trying dependency injection for test cases, wondering if it is possible to do that for testing.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;

class PageController extends Controller
{
    protected $request;
    protected $user;

public function __construct(Request $request, User $user)
{
    $this->user    = $user;
    $this->request = $request;
}

This is how I usually do dependency injection. For example, the following line gets an array instance of all the users.

$users = $this->user->all();

I'd like to do the same thing for 'TestCase'. Here is an excerpt of the code.

use App\User;
use Illuminate\Http\Request;

class ViewTest extends TestCase
{
    protected $request;
    protected $user;

public function __construct(Request $request, User $user)
{
    $this->user    = $user;
    $this->request = $request;
}

This causes the following error.

PHP Fatal error: Uncaught TypeError: Argument 1 passed to ViewTest::__construct() must be an instance of Illuminate\Http\Request, none given, called in phar

It sounds like that __construct() must be an instance of Request, but I don't understand what it actually means, since this code works in, let's say controller classes.

I've searched Laravel's documentation, but I'm not really sure if it's possible to do dependency injection for testing.

I'd appreciate if you would give any advice.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire