如何在PHPUnit中测试;使用Laravel编写的API上传CSV文件?

时间:2016-06-02 06:58:36

标签: php unit-testing laravel csv phpunit

我想通过Laravel API上传CSV文件,然后使用PHPUnit测试上传。

我的$('iframe').contents().find('html').html('<html><body>test</body></html>'); 功能在Controller和store()功能中基本上是什么样的。

这是我到目前为止所得到的:

testCreate()

,控制器方法如下:

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ProspectListControllerTest extends TestCase
{

use WithoutMiddleware, DatabaseTransactions;

public function testCreate()
{

    $file = new Symfony\Component\HttpFoundation\File\UploadedFile(storage_path('/crm/data/test-file.csv'), 'test-file.csv', 'text/plain', 446, null, true);

    $this->call('POST', '/api/lists-imports/', [], [], ['csv_file' => $file]);
    $this->dump()->assertResponseOk();
  }
}

任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:1)

这是我的功能测试Laravel 6及更高版本的示例(“ uploads”是我的存储驱动程序):

    use Illuminate\Http\UploadedFile;

    Storage::fake('uploads');

    $header = 'Header 1,Header 2,Header 3';
    $row1 = 'value 1,value 2,value 3';
    $row2 = 'value 1,value 2,value 3';

    $content = implode("\n", [$header, $row1, $row2]);

    $inputs = [
        'csv_file' =>
            UploadedFile::
                fake()->
                createWithContent(
                    'test.csv',
                    $content
                )
    ];


    $response = $this->postJson(
        'file-upload',
        $inputs

    );

    $response->assertOk();

答案 1 :(得分:0)

在Laravel中有一种测试文件上传的新方法。 https://laravel-news.com/testing-file-uploads-with-laravel

就像这样:(来自文档)

   public function testAvatarUpload()
{
    Storage::fake('avatars');

    $response = $this->json('POST', '/avatar', [
        'avatar' => UploadedFile::fake()->image('avatar.jpg')
    ]);

    // Assert the file was stored...
    Storage::disk('avatars')->assertExists('avatar.jpg');

    // Assert a file does not exist...
    Storage::disk('avatars')->assertMissing('missing.jpg');
}