Laravel5 对登录表单进行单元测试

Laravel5 Unit Testing a Login Form

我 运行 下面的测试,我收到 failed_asserting 错误是正确的。有人可以进一步解释为什么会这样吗?

/** @test */
public function a_user_logs_in()
{
    $user =  factory(App\User::class)->create(['email' => 'john@example.com', 'password' => bcrypt('testpass123')]);

    $this->visit(route('login'));
    $this->type($user->email, 'email');
    $this->type($user->password, 'password');
    $this->press('Login');
    $this->assertTrue(Auth::check());
    $this->seePageIs(route('dashboard'));
}

您的 PHPUnit 测试是一个客户端,而不是 Web 应用程序本身。因此 Auth::check() 不应该 return 为真。相反,您可以在按下按钮后检查您是否在正确的页面上,并且您会看到某种确认文本:

    /** @test */
    public function a_user_can_log_in()
    {
        $user = factory(App\User::class)->create([
             'email' => 'john@example.com', 
             'password' => bcrypt('testpass123')
        ]);

        $this->visit(route('login'))
            ->type($user->email, 'email')
            ->type('testpass123', 'password')
            ->press('Login')
            ->see('Successfully logged in')
            ->onPage('/dashboard');
    }

我相信大多数开发人员都会这样做。即使 Auth::check() 有效——这仅意味着创建了一个会话变量,您仍然需要测试您是否已正确重定向到正确的页面等。

在您的测试中,您可以使用您的模型获取用户,并且您可以使用 ->be($user) 以便它获得身份验证。

所以我在我的测试用例中写了 API 测试

    $user = new User(['name' => 'peak']);
    $this->be($user)
         ->get('/api/v1/getManufacturer')
          ->seeJson([
             'status' => true,
         ]);

对我有用