1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > php 测试控制器 php – 控制器的Laravel单元测试

php 测试控制器 php – 控制器的Laravel单元测试

时间:2022-02-19 00:47:06

相关推荐

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@','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@',];

Auth::shouldReceive('attempt')

->once()

->with($credentials)

->andReturn(true);

$this->call('POST',$credentials);

$this->assertRedirectedTo('home');

}

}

再次,总是想想你真正想要测试的内容.你真的需要知道在哪个路由上触发哪个控制器动作?或者视图的名称被返回?实际上,您只需要确保控制器实际上尝试这样做.您传递一些数据,然后测试它是否按预期行为.

并且始终确保您不尝试测试任何框架功能,例如,如果特定路由触发特定操作或视图正确加载.这已经被测试了,所以你不需要担心.专注于您的应用程序的功能,而不是基础框架.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。