在Laravel中进行测试时,可以充当用户的id

在Laravel中进行测试时,可以充当用户的id

问题描述:

Laravel 5.7. I have a test like this:

/** @test */
public function do_nothing_test()
{
    $user = factory(User::class)->states('app')->make();
    $this->actingAs($user, 'api');
    $response = $this->postJson('some_endpoint', ['foobar' => 3]);
    $this->assertEquals(1, Foobar::count());
}

which calls an endpoint in a controller that tries to get the logged in user:

public function update_foobar($request)
{
    $userId = auth()->user()->id;
    Foobar::create(['userId' => $userId, 'foobar' => $request->foobar]);
}

The value of $id is null. How can I get the test to work so that the user's details are available to the controller?

Laravel 5.7。 我有这样的测试: p>

  / ** @test * / 
public function do_nothing_test()
 {
 $ user = factory(User :: class) -  > states('app') - > make(); 
 $ this-> actsAs($ user,'api'); 
 $ response = $ this-> postJson('some_endpoint',['  foob​​ar'=> 3]); 
 $ this-> assertEquals(1,Foobar :: count()); 
} 
  code>  pre> 
 
 

调用 控制器中尝试获取登录用户的端点: p>

  public function update_foobar($ request)
 {
 $ userId = auth() - > user  () - > id; 
 Foobar :: create(['userId'=> $ userId,'foobar'=> $ request-> foobar]); 
} 
  code>   pre> 
 
 

$ id code>的值为 null code>。 如何让测试工作以便控制器可以使用用户的详细信息? p> div>

$user = factory(User::class)->states('app')->make();

make() doesn’t save to the database, so they won’t have an ID. I think you mean create()?