php 测试控制器,php – 控制器的Laravel单元测试
好的,如已經在評論中已經解釋了一點,我們先回退一下,再考慮一下這種情況.
“My first step is to check that the /login controller is called on the home url.”
所以這意味著:當用戶點擊主路由時,您需要檢查用戶是否登錄,如果不是,您需要將其重定向到登錄名,或許有一些Flash消息.登錄后,您要將其重定向到主頁.如果登錄失敗,您需要將它們重定向到登錄表單,也可能使用Flash消息.
所以有幾件事要測試:家用控制器和登錄控制器.所以遵循TDD的精神,讓我們先創建測試.
注意:我將遵循phpspec使用的一些命名約定,但不要讓你煩惱.
class HomeControllerTest extends TestCase
{
/**
* @test
*/
public function it_redirects_to_login_if_user_is_not_authenticated()
{
Auth::shouldReceive('check')->once()->andReturn(false);
$response = $this->call('GET','home');
// Now we have several ways to go about this,choose the
// one you're most comfortable with.
// Check that you're redirecting to a specific controller action
// with a flash message
$this->assertRedirectedToAction(
'AuthenticationController@login',null,['flash_message']
);
// Only check that you're redirecting to a specific URI
$this->assertRedirectedTo('login');
// Just check that you don't get a 200 OK response.
$this->assertFalse($response->isOk());
// Make sure you've been redirected.
$this->assertTrue($response->isRedirection());
}
/**
* @test
*/
public function it_returns_home_page_if_user_is_authenticated()
{
Auth::shouldReceive('check')->once()->andReturn(true);
$this->call('GET','home');
$this->assertResponSEOk();
}
}
這就是家庭控制器.在大多數情況下,您實際上不在乎您被重定向到哪里,因為這可能會隨時間而變化,您將不得不更改測試.所以至少應該做的是檢查你是否被重定向,只有檢查更多的細節,如果你真的認為這是重要的測試.
我們來看看認證控制器:
class AuthenticationControllerTest extends TestCase
{
/**
* @test
*/
public function it_shows_the_login_form()
{
$response = $this->call('GET','login');
$this->assertTrue($response->isOk());
// Even though the two lines above may be enough,// you could also check for something like this:
View::shouldReceive('make')->with('login');
}
/**
* @test
*/
public function it_redirects_back_to_form_if_login_fails()
{
$credentials = [
'email' => 'test@test.com','password' => 'secret',];
Auth::shouldReceive('attempt')
->once()
->with($credentials)
->andReturn(false);
$this->call('POST','login',$credentials);
$this->assertRedirectedToAction(
'AuthenticationController@login',['flash_message']
);
}
/**
* @test
*/
public function it_redirects_to_home_page_after_user_logs_in()
{
$credentials = [
'email' => 'test@test.com',];
Auth::shouldReceive('attempt')
->once()
->with($credentials)
->andReturn(true);
$this->call('POST',$credentials);
$this->assertRedirectedTo('home');
}
}
再次,總是想想你真正想要測試的內容.你真的需要知道在哪個路由上觸發哪個控制器動作?或者視圖的名稱被返回?實際上,您只需要確保控制器實際上嘗試這樣做.您傳遞一些數據,然后測試它是否按預期行為.
并且始終確保您不嘗試測試任何框架功能,例如,如果特定路由觸發特定操作或視圖正確加載.這已經被測試了,所以你不需要擔心.專注于您的應用程序的功能,而不是基礎框架.
總結
以上是生活随笔為你收集整理的php 测试控制器,php – 控制器的Laravel单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql行转列函数_一个小知识点-Hi
- 下一篇: php使用七牛直播,七牛上传文件,PHP