【问题标题】:Why would the example test in Laravel fail for redirect?为什么 Laravel 中的示例测试会因重定向失败?
【发布时间】:2014-04-19 09:26:13
【问题描述】:

请解释为什么 Laravel 4 的示例测试对我来说失败了。

我的“/”路由重定向到我的 routes.php 文件中的“登录”。

(哦,我已经 RTFMed 并搜索了几个网站、博客和 tuts。)

-sh-3.2$ phpunit
PHPUnit 4.0.7 by Sebastian Bergmann.

Configuration read from /home/dev/phpunit.xml

The Xdebug extension is not loaded. No code coverage will be generated.

F

Time: 83 ms, Memory: 13.50Mb

There was 1 failure:

1) ExampleTest::testBasicExample
Failed asserting that false is true.

/home/dev/app/tests/ExampleTest.php:14

FAILURES!                            
Tests: 1, Assertions: 1, Failures: 1.
-sh-3.2$ 

这是来自 ExampleTest.php 的代码

<?php

class ExampleTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $crawler = $this->client->request('GET', '/');

        $this->assertTrue($this->client->getResponse()->isOk());
    }

}

【问题讨论】:

  • 没有测试代码,很难判断
  • 注意:将标题更改为重定向失败

标签: laravel-4 phpunit eloquent


【解决方案1】:

测试失败,因为您得到的是 302 状态码而不是 200(因为默认的 routes.php 文件中没有重定向)。

如果你想测试重定向,那么 Laravel 提供了几种方法。

  1. 如果您使用命名路由:

    $this-&gt;assertRedirectedToRoute('login');

  2. 如果没有:

    $this-&gt;assertRedirectedTo('login');

  3. 用于测试响应状态代码:

    $this-&gt;assertResponseStatus(302);

【讨论】:

  • 谢谢。这是了解这条兔子足迹的良好开端。在我标记最佳答案之前会注意更多答案。
  • 我怀疑你会得到更多答案,因为这是正确的答案。
  • 这个答案并没有解释为什么会发生重定向(至少不是以我能理解的方式)。我希望与所描述的 routes.php 文件有关,但尚不清楚那里的确切含义。 IE。这是什么意思? – “因为有一个不在默认 routes.php 中的重定向”。他怎么知道有重定向?在代码中哪里可以看到这种重定向?怎么可能禁用它?
  • 顺便说一句,我没有故意否决这个答案,现在它不会让我改变我的投票:(
  • @geoidesic 我本来可以更好的措辞。 OP 修改了 routes.php 并且默认路由 (/) 正在重定向到其他地方而不是显示视图。测试未更新以反映更改,因此失败。
猜你喜欢
  • 2013-08-06
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多