【问题标题】:Testing Laravel-Excel download测试 Laravel-Excel 下载
【发布时间】:2015-08-07 10:54:13
【问题描述】:

我正在使用以下包:https://github.com/Maatwebsite/Laravel-Excel 版本 2 和 Laravel 版本 5.1

我有以下代码的控制器方法:

....
return Excel::create('List', function($excel) use ($list)
{
  $excel->sheet('List', function($sheet) use ($list)
  {
    $sheet->fromModel($list);
  });
})
->download('csv');  

和这样的简单测试:

$this->call('GET', 'route/to/csv', [
    'param' => 'value',
]);

$this->dump();

上面的测试输出[ERROR]: Headers already sent来自包的this line

控制器方法工作正常,但无法测试。

我尝试使用 --stderr 参数运行 phpunit。在这种情况下,不会引发错误,但它只是将 CSV 文件的输出转储到控制台并退出。 我还尝试使用 @runInSeparateProcess 注释运行测试并得到如下错误:

PHPUnit_Framework_Exception: PHP Notice:  Constant LARAVEL_START already defined in bootstrap/autoload.php on line 3
....
PHP Fatal error:  Uncaught exception 'ReflectionException' with message 'Class env does not exist' in vendor/laravel/framework/src/Illuminate/Container/Container.php:736

这可能是 Laravel-Excel 包中的错误还是我测试错了?

【问题讨论】:

    标签: laravel phpunit laravel-5.1 laravel-excel


    【解决方案1】:

    那是因为 download 方法在 laravel-excel 中的工作方式是设置标题。您想避免这种情况,而是通过返回 laravel 响应自己完成所有工作。

    试试这个:

    $file = Excel::create('List', function($excel) use ($list) {
      $excel->sheet('List', function($sheet) use ($list)
      {
        $sheet->fromModel($list);
      });
    })->string('xls');
    
    return new Response($file, 200, [
                'Content-Type' => 'application/vnd.ms-excel; charset=UTF-8',
                'Content-Disposition' => 'attachment; filename="' . $file->filename . '.' . $file->ext . '"',
                'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past
                'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'),
                'Cache-Control' => 'cache, must-revalidate',
                'Pragma' => 'public',
            ]);
    

    主要区别在于使用string() 方法,该方法将返回excel文件的二进制数据,并允许您将其作为响应数据传递。

    【讨论】:

    • 我试过了,它抛出了一个异常:响应内容必须是一个字符串或实现__toString()的对象,给定的“对象”。
    • @FelipeR.Saruhashi 您需要导入 Illuminate\Http\Response 而不是 Facade 的 \Response
    • 我花了一整天的时间终于让它开始工作了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多