测试用户是否已登录laravel 5.7

时间:2019-01-04 18:08:05

标签: php laravel phpunit

我正在测试,但是在尝试检查用户是否登录时失败:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use App\User;

class RegisterTest extends TestCase
{

    use RefreshDatabase;

    /*.....
    more test about registering
     ....*/    

    /** @test */
    function redirect_to_home_page_and_logged_in_after_login()
    {                   

        $user = factory(User::class)->create([
            'name' => 'Test',
            'email' => 'test@hotmail.com', 
            'password' => '123456'
        ]);     

        $response = $this->post('login', [
            'email' => 'test@hotmail.com',
            'password' => '123456'          
        ]);

        //this works
        $response->assertRedirect('/');

        //this fails 
        $this->assertTrue(Auth::check());


    }
}

这是我的控制器HomeController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{


    public function index()
    {                    

        if (Auth::check()){

            return view('home');    
        }

        return view('welcome');

    }
}

这是我的路线/web.php

Route::get('/', 'HomeController@index');    
Auth::routes();

我不确定自己在做什么错。我能做什么?。我正在使用laravel 5.7和phpunit 5.7.1 同样在我的app / Htpp / Auth / LoginController.php中,我这样做:

protected $redirectTo = '/'; 

谢谢。

2 个答案:

答案 0 :(得分:1)

创建用户需要您注意密码的散列。 您只需使用php的password_hash函数即可完成此操作。并使用Auth::login($user);登录。

像这样:

$user = User::create(['email' => 'r@o.b', 'password' => password_hash('123456', 1)]);
Auth::login($user); //You should be logged in :)

答案 1 :(得分:1)

除了对密码进行哈希处理之外,您还可以将其发布到注册路线并创建一个新帐户。

/** @test */
function redirect_to_home_page_and_logged_in_after_register()
{                      
    $response = $this->post('register', [
        'name' => 'Test',
        'email' => 'test@hotmail.com',
        'password' => '123456'          
    ]);

    //this works
    $response->assertRedirect('/');

    //this fails 
    $this->assertTrue(Auth::check());
}

我想您可能还需要同时做这两种方式:

/** @test */
function redirect_to_home_page_and_logged_in_after_login()
{                

    $user = factory(User::class)->create([
        'name' => 'Test',
        'email' => 'test@hotmail.com', 
        // note you need to use the bcrypt function here to hash your password
        'password' => bcrypt('123456')
    ]);      

    $response = $this->post('login', [
        'name' => 'Test',
        'email' => 'test@hotmail.com',
        'password' => '123456'          
    ]);

    //this works
    $response->assertRedirect('/');

    //this fails 
    $this->assertTrue(Auth::check());
}