Login 與 Logout
登入與登出的測試
use Illuminate\Support\Facades\Session;
class AuthControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
Session::start();
}
public function testLoginInvalidInput()
{
$this->call('POST', 'auth/login', [
'_token' => csrf_token(),
]);
$this->assertHasOldInput();
$this->assertSessionHasErrors();
$this->assertResponseStatus(302);
}
public function testLoginSuccess()
{
$guardMock = Mockery::mock('Illuminate\Auth\Guard');
$this->app->instance('Illuminate\Contracts\Auth\Guard', $guardMock);
$guardMock
->shouldReceive('check')
->once()
->andReturn(false);
$guardMock
->shouldReceive('attempt')
->once()
->andReturn(true);
$this->call('POST', 'auth/login', [
'email' => '[email protected]',
'password' => 'password',
'_token' => csrf_token(),
]);
$this->assertRedirectedTo('home');
}
public function testLoginFailed()
{
$guardMock = Mockery::mock('Illuminate\Auth\Guard');
$this->app->instance('Illuminate\Contracts\Auth\Guard', $guardMock);
$guardMock
->shouldReceive('check')
->once()
->andReturn(false);
$guardMock
->shouldReceive('attempt')
->once()
->andReturn(false);
$this->call('POST', 'auth/login', [
'email' => '[email protected]',
'password' => 'password',
'_token' => csrf_token(),
]);
$this->assertHasOldInput();
$this->assertSessionHasErrors();
$this->assertRedirectedTo('auth/login');
}
public function testLogout()
{
$this->userLoggedIn();
$guardMock = Mockery::mock('Illuminate\Auth\Guard');
$this->app->instance('Illuminate\Contracts\Auth\Guard', $guardMock);
$guardMock
->shouldReceive('logout')
->once();
$this->call('GET', 'auth/logout');
$this->assertRedirectedTo('/');
}
public function testRegister()
{
}
重構測試
protected function doesLoginPass($pass)
{
$guardMock = Mockery::mock('Illuminate\Auth\Guard');
$this->app->instance('Illuminate\Contracts\Auth\Guard', $guardMock);
$guardMock
->shouldReceive('check')
->once()
->andReturn(false);
$guardMock
->shouldReceive('attempt')
->once()
->andReturn($pass);
$this->call('POST', 'auth/login', [
'email' => '[email protected]',
'password' => 'password',
'_token' => csrf_token(),
]);
if ($pass) {
$this->assertRedirectedTo('home');
} else {
$this->assertHasOldInput();
$this->assertSessionHasErrors();
$this->assertRedirectedTo('auth/login');
}
}
}