问题描述
我是单元测试的新手,我想尝试测试我的登录页面我对这个单元的目标是:-> 如果它在数据库中匹配 -> 重定向到路由'/'-> 如果不是 -> 重定向到路由 '/login'
I'm pretty new on unit testing and I want to try to test my login pagemy Goal for this unit are :-> if it match in database -> redirect to route '/'-> if not -> redirect to route '/login'
<?php
namespace TestsFeature;
use AppDomainCoreModelsUser;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesSession;
use TestsTestCase;
use IlluminateFoundationTestingWithoutMiddleware;
use IlluminateFoundationTestingDatabaseMigrations;
use IlluminateFoundationTestingDatabaseTransactions;
class userTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic test example.
*
* @return void
*/
public function testLoginTrue()
{
$credential = [
'email' => '[email protected]',
'password' => 'user'
];
$this->post('login',$credential)->assertRedirect('/');
}
public function testLoginFalse()
{
$credential = [
'email' => '[email protected]',
'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' => '[email protected]',
'password' => 'user'
];
$this->post('login',$credential)
->assertRedirect('/')
->get('/login')
->assertRedirect('/');
}
但是...它返回
1) 测试功能用户测试::testLoginTrue BadMethodCallException:重定向上不存在方法 [get].
那么如何正确做呢?
提前致谢
推荐答案
我也有点卡在 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' => '[email protected]',
'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 + 多进程测试登录凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!