我有以下方法用于中间件
public function handle(Request $request, Closure $next)
{
/**
* test if user is logged in User
*/
if(!$this->auth->check())
{
/**
* if user email register arbitrary User
*/
if(!$request->has('email'))
{
return back()
->with('error', "Please submit an email address!");
}
$user = $this->registerUser($request->input('email'));
/**
* [$user register a new user and set session]
* @var Request
*/
$request->session()->set('user', $user);
}
return $next($request);
}
我是PHPUNIT和单元/功能测试的新手,所以我开始使用
public function testHasSession()
{
$faker = \Faker\Factory::create();
Session::shouldReceive('get')
->once()
->with('user');
$response = $this->middleware->handle(Request::create(route('brokerquotes.request.store'), 'POST', ['email'=> $faker->email]), function ($request) {
return 'OK';
});
$this->assertResponseOK();
}
但它不起作用。如何测试请求会话已设置,以及在触发与中间件绑定的相应路由时调用的控制器方法...?
答案 0 :(得分:1)
您可以这样做:
public function testHasSession()
{
$faker = \Faker\Factory::create();
$email = $faker->email;
$this->post(route('brokerquotes.request.store'), ['email'=> $email]);
$this->assertResponseOk();
$this->assertEquals($email, session('user')->email);
}
...假设您的用户实体有一个字段email
。