模拟内容上传的文件 [英] Mocking an uploaded file with content

查看:53
本文介绍了模拟内容上传的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个Laravel项目,该项目利用GraphQL和Lighthouse作为后端API.对于某些端点,我们具有文件上传支持.我们已经成功测试了.

I'm working on a Laravel project that utilizes GraphQL with Lighthouse for the backend API. For some of the endpoints, we have file upload support. We have successfully tested that.

我们现在正在创建的新端点也将支持文件上传.但是,我们不仅需要将文件存储在服务器上的某个位置,还必须读取该文件的内容,然后根据此内容执行某些操作.

The new endpoint that we are creating right now, will also support a file upload. But instead of just storing the file somewhere on our server, we have to read the contents of this file and do something depending on this content.

我们当然要测试这个新功能.但是要做到这一点.我们必须模拟具有特定内容的上传文件进行测试.我所能找到的只是一个伪造的 UploadedFile :: fake()方法,它为您创建了一个随机/空文件.

We want to test this new feature, ofcourse. But to do that. We have to mock an uploaded file, with specific contents, to test this. All I could find was just a fake UploadedFile::fake() method that creates a random/empty file for you.

我知道我可以为此创建单元测试.但是我真的很想添加一个端到端测试.

I know I could create unit tests for this. But I really want to add an end-to-end test.

官方灯塔文档具有以下内容代码示例:

The official lighthouse docs has the following code example:

<?php

$this->multipartGraphQL(
    [
        'operations' => /* @lang JSON */
            '
            {
                "query": "mutation Upload($file: Upload!) { upload(file: $file) }",
                "variables": {
                    "file": null
                }
            }
        ',
        'map' => /* @lang JSON */
            '
            {
                "0": ["variables.file"]
            }
        ',
    ],
    [
        '0' => UploadedFile::fake()->create('image.jpg', 500),
    ]
)

我需要用我自己创建的模拟替换该上传文件.也许像这样:

I need to replace that uploaded file with a mock that I created myself. Maybe something like:

<?php

UploadedFile::fake()
    ->fromPath('example/file/in/my/testsuite.obj')
    ->create()

我可以通过任何内置方式来设置伪造的上传文件的内容吗?还是我可以用自己的工厂逻辑扩展类?

Is there any build-in way I can set the content of a fake uploaded file? Or is there any way I can extend the class with my own factory logic?

推荐答案

要基于测试文件在Laravel中伪造文件,可以使用 new File .该类是 Illuminate \ Http \ File .

To fake a file in Laravel based on test file you can use new File. The class is Illuminate\Http\File.

构造函数采用一个路径,并从该文件路径给您一个文件.因此,以您的示例为例,伪文件将通过以下方式创建

The constructor takes a path and gives you a file from that file path. So to use your example, the fake file would be created the following way

new File('example/file/in/my/testsuite.obj')

然后,您只需要将发送给Lighthouse的文件设置为该文件即可.

You then just need to set the file you sent to Lighthouse to that file.

这篇关于模拟内容上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆