【问题标题】:Laravel 5 how to test redirectLaravel 5 如何测试重定向
【发布时间】:2016-07-18 14:04:06
【问题描述】:

我有一个 Laravel 5 应用程序,其中一个控制器操作通过重定向到 Laravel 应用程序外部但位于同一域中的页面来完成。手动与页面交互可以正常工作,但使用 PHPunit 自动化测试则不行。它不断尝试加载路由并失败并显示“标头已发送”。

路线

Route::post('/trials', [
    'middleware' => ['web'],
    'uses' => 'TrialsController@create'
]);

控制器

public function create(Request $request)
{
  ...
  setcookie( 'etc', $value, time() + 60, '/', "domain.com", true, true) ;
  return Saml2::login('https://store.domain.com');
}

测试

public function testSuccessfulSignup(){

    $this->visit('/signup')
        ->type('test@mail.com', 'mail')
        ->type('Philip', 'first_name')
        ->type('Fry', 'last_name')
        ->press('Signup !') ;
        // ->seePageIs('https://store.domain.com'); doesn't work
        // ->assertRedirectedTo('https://store.domain.com'); doesn't work
}

错误

1) TrialsTest::testSuccessfulSignup
A request to [http://domain.com/trials] failed. Received status code [500].

/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:114
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:554
/private/var/identity/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:541
/private/var/identity/tests/TrialsTest.php:154

Caused by
exception 'ErrorException' with message 'Cannot modify header information - headers already sent by (output started at phar:///usr/local/bin/phpunit/phpunit/Util/Printer.php:134)' in /private/var/identity/app/Http/Controllers/TrialsController.php:84

更新

这似乎与网络中间件有关,更具体地说是 CSRF 中间件,干扰了我的重定向标头。指定use WithoutMiddleware; 也会禁用会话,我怎样才能保留会话但在测试上下文中禁用 CSRF?

更新 2

关于关闭投票:您可以在测试代码中看到我断言它应该遵循重定向,我希望此代码执行的操作是遵循控制器操作之外的重定向(成功且不失败)然后继续执行更多验证。

【问题讨论】:

  • 请回答您的问题
  • @surfer190 我没有答案,它不起作用。我认为这可能是驱动程序的限制,或者我正在使用单元测试来做一些他们不适合的事情

标签: php laravel-5 phpunit


【解决方案1】:

在进程隔离中运行测试或整个套件似乎终于可以工作了。这可能已经通过更新 phpunit 得到改进,因为它以前没有任何效果。

通过命令行运行:

phpunit --process-isolation --filter <method>

或者在phpunit.xml中:

<phpunit ...
         processIsolation="true"
         stopOnFailure="false">
<testsuites>
</testsuites>
</phpunit>

显然测试代码也需要重定向。

$this->doStuff()
     ->assertRedirect($url);

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 2016-12-13
    • 1970-01-01
    • 2015-12-18
    • 2021-08-25
    • 2018-03-31
    • 2015-08-04
    • 2016-04-06
    • 2015-04-08
    相关资源
    最近更新 更多