php - 测试用户是否登录 laravel 5.7

标签 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());


    }
}

这是我的 Controller 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 = '/'; 

谢谢你。

最佳答案

除了散列您的密码之外,您还可以发布到注册路径并创建一个新帐户。

/** @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());
}

关于php - 测试用户是否登录 laravel 5.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54044025/

相关文章:

laravel - 所需的验证在 laravel darkaonline swagger UI 中不起作用

PHPUnit:为自定义断言编写测试

php - 项目编码标准与单元测试代码覆盖率冲突怎么办?

php - 将 WooCommerce 'Shop' 页面转发到站点上的另一个页面

php - Laravel 与条件的多对多关系

php - Laravel - 如何将参数传递给路由?有更好的做法吗?

javascript - 如何在 react.js 中包含 html View 文件

php - Codeigniter 选择加入给出重复结果

javascript - 使用 content editable 通过 ajax 和 PHP 提交更改

PHPUnit:现有对象的模拟方法