1

我正在尝试熟悉 Kohana 中的 PHPUnit 测试。目前,我的代码中的 Request::current()->redirect 调用似乎存在问题。

例如,我正在尝试测试登录功能。一旦我们的用户成功登录,我们使用上面的请求重定向行将其重定向到其主页。问题是当那条线在那里时,测试似乎停在那里并且永远不会返回结果。

这是我目前的测试编写方式:

class SampleTest extends Kohana_UnitTest_TestCase
{
protected $session;

public function setUp() {
    parent::setUp();
    $this->session = Session::instance();
}

public function testLogin()
{   
    $request = new Request('/login');
    $request->method(HTTP_Request::POST)
        ->post(array('username' => 'username', 'password' => 'password'));
    $request->execute();

    $this->assertEquals($this->session->get('username'), 'password');
 }
}

如果我在登录控制器中注释掉以下行,一切正常:

Request::current()->redirect(); //redirect to home

我究竟做错了什么?

4

2 回答 2

1

标准请求的操作顺序(检查您的 index.php)是:

  1. 执行
  2. 发送标题
  3. 身体

您在执行过程中劫持了请求并重定向了该过程。您的测试只是遵循该代码,因为它是该执行的所有部分。

相反,通过将重定向添加到在 send_headers 中执行的请求标头来延迟您的重定向,并且您不会在单元测试中遇到该代码。将您的 Request::current()->redirect() 行替换为重定向用户的正确方法:

$this->response->headers("Location", URL::site(NULL, TRUE));
于 2012-03-29T03:30:32.050 回答
0

I think the best way to test redirects in Kohana is to extend the Request class with a Unittest_Request.

Add a redirect method to the Unittest_Request class which uses the Location header.

Add some helper methods to your tests for creating get and post requests using Unittest requests.

Write assert methods like assertRedirectedTo, assertResponse.... and so on.

I know this is a lot, but it would really help you in a longer term.

于 2012-04-03T19:10:55.627 回答