Laravel使用phpunit + multiprocess测试登录凭证 [英] Laravel Testing login Credential using phpunit + multiprocess
问题描述
我对单元测试还很陌生,我想尝试测试我的登录页面 我对该单元的目标是: ->如果在数据库中匹配->重定向到路由'/' ->如果不是->重定向到路由"/登录"
I'm pretty new on unit testing and I want to try to test my login page my Goal for this unit are : -> if it match in database -> redirect to route '/' -> if not -> redirect to route '/login'
<?php
namespace Tests\Feature;
use App\Domain\Core\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class userTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic test example.
*
* @return void
*/
public function testLoginTrue()
{
$credential = [
'email' => 'user@ad.com',
'password' => 'user'
];
$this->post('login',$credential)->assertRedirect('/');
}
public function testLoginFalse()
{
$credential = [
'email' => 'user@ad.com',
'password' => 'usera'
];
$this->post('login',$credential)->assertRedirect('/login');
}
}
当我在TestLoginTrue上测试时,它成功返回到'/',但是当我尝试TestLoginFalse ...它返回与TestLoginTrue相同的结果时,它应该停留在'/login'路线上, 有想法吗?
when I test on TestLoginTrue , its successfully return to '/' But when i try the TestLoginFalse ... it return same like TestLoginTrue, it should be stayed on '/login' route, Any Idea?
此外,我想尝试检查是否已经登录但无法访问登录页面,所以我的最初想法是: 公共功能testLoginTrue()
Plus I want to try to check if when I already login I couldn't access the login page so my initial idea is : public function testLoginTrue()
{
$credential = [
'email' => 'user@ad.com',
'password' => 'user'
];
$this->post('login',$credential)
->assertRedirect('/')
->get('/login')
->assertRedirect('/');
}
但是...它会返回
1)Tests \ Feature \ userTest :: testLoginTrue BadMethodCallException: 方法[get]在重定向上不存在.
1) Tests\Feature\userTest::testLoginTrue BadMethodCallException: Method [get] does not exist on Redirect.
那如何正确地做呢?
预先感谢
推荐答案
我对Laravel 5.4的测试也有些困惑,请按照重定向案例进行操作.
I am also a bit stuck with Laravel 5.4 testing follow redirects case.
作为解决方法,您可以检查$response->assertSessionHasErrors()
.这样就可以正常工作:
As a workaround, you may check $response->assertSessionHasErrors()
. This way it should work:
public function testLoginFalse()
{
$credential = [
'email' => 'user@ad.com',
'password' => 'incorrectpass'
];
$response = $this->post('login',$credential);
$response->assertSessionHasErrors();
}
此外,您可以在testLoginTrue()
中检查该会话缺少错误:
Also, in testLoginTrue()
you may check, that session missing errors:
$response = $this->post('login',$credential);
$response->assertSessionMissing('errors');
希望这会有所帮助!
这篇关于Laravel使用phpunit + multiprocess测试登录凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!