Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何正确地调用laravel';phpunit中的中间件关闭?_Php_Laravel_Laravel 5_Controller_Laravel Middleware - Fatal编程技术网

如何正确地调用laravel';phpunit中的中间件关闭?

如何正确地调用laravel';phpunit中的中间件关闭?,php,laravel,laravel-5,controller,laravel-middleware,Php,Laravel,Laravel 5,Controller,Laravel Middleware,如何在phpunit测试中正确调用此中间件关闭函数,以便设置$user Auth::user将被模拟,并将接收正确的用户对象,但在创建控制器实例时不会调用该函数 这是我的密码: use App\Http\Controllers\Controller; class CustomController extends Controller { private $user; public function __construct() { $this->m

如何在
phpunit
测试中正确调用此中间件关闭函数,以便设置
$user

Auth::user将被模拟,并将接收正确的用户对象,但在创建控制器实例时不会调用该函数

这是我的密码:

use App\Http\Controllers\Controller;

class CustomController extends Controller
{
    private $user;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->user = Auth::user();
            return $next($request);
        });
    }
}
Phpunit:

use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Controllers\CustomController;

class CustomControllerTest extends TestCase
{
   use CreatesApplication;

   private $customController;

   public function setUp()
   {
      Auth::shouldReceive('user')->andReturn(new User());
      $this->customController = $this->app->make(CustomController::class);
   }
}

您正在从容器中解析控制器,但没有向其传递任何要处理的请求。您的中间件代码将仅在控制器被赋予某些处理时执行

因此,
$this->middleware(…)
只是简单地说“当通过管道发送请求时执行此中间件”

只需测试到达端点的标准请求,然后断言需要断言的内容

$this->get('your_endpoint');

显示“创建控制器实例”的代码在
\uu construct()