Laravel phpunit 测试 maatwebsite/excel 导入

Laravel phpunit test maatwebsite/excel import

我已经创建了一个 maatwebsite/excel 导入例程,我想测试它。

maatwebsite/excel 测试页面除了伪造它之外没有向我提供任何其他信息。 但我需要上传我的真实 excel 文件,因为我想验证 excel 文件中的数据是否被正确处理。

这是我的上传输入字段和相应的点击终点的按钮/import

<form action="/import" method="post" enctype="multipart/form-data">
   @csrf
   <div class="form-group">
       <input type="file" class="form-control-file file-path" name="fileToUpload">
   </div>
   <button type="submit" class="btn btn-primary">Import File</button>
</form>

在视图的控制器端,将处理并导入上传的文件。

...

public function store(Request $request) {
        $request->validate([
            'fileToUpload' => 'required|file|max:4096|mimes:xls,xlsx',
        ]);

        // start the import
        Excel::import(new SheetNavigator, request()->file('fileToUpload'));
...

需要导入的文件位于我的测试环境下:

/tests
  /files
    /myexcel.xlsx
public function test_user_can_import_file() {

        Excel::fake();

        $datafile = new UploadedFile(
            base_path('tests/files/myfile.xlsx'),
            'myfile.xlsx',
            'xlsx',
            13071,
            true);

        $res = $this->post('/import', [
            'fileToUpload' => $datafile
        ]);

        // asserting, that everything works..

    }

我需要一个测试来验证上传是否成功以及导入例程是否被触发。 我尝试了一切,从伪造任何东西到使用存储。

感谢任何帮助,谢谢!

克里斯

一般来说,实现此目的的理想方法是模拟 Excel class,然后检查是否已使用给定文件调用了 import。尽管这似乎是一个静态调用,但它实际上是一个 Facade 调用,因此您可以将其替换为模拟。事实上,它似乎自己提供了这个功能:

public function testThatItImportsTheUploadedFile() {
    $file = UploadedFile::fake()->create('myexcel.xlsx');

    Excel::fake();

    $this->post('/import', [
        'fileToUpload' => $file
    ]);

    Excel::assertImported('myexcel.xlsx');

}

注意:这验证端点是否按预期工作,因为文件已上传并且 Excel::import 将按预期工作。

如果你想用你的真实文件进行测试,你可以创建一个新的 UploadedFile 实例(链接 symfony 基础 class 因为这是构造函数所在的地方)。

$file = new UploadedFile(
    base_path('tests/files/myfile.xlsx'),
    'myfile.xlsx',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    null,
    true
);