2016-06-02 18 views
5

Tôi muốn tải lên tệp CSV qua API Laravel rồi thử tải lên bằng PHPUnit.Cách kiểm tra trong PHPUnit; tệp CSV Tải lên bằng API được viết bằng Laravel?

Chức năng store() của tôi trong Bộ điều khiển và chức năng testCreate() về cơ bản là như thế nào.

Đây là những gì tôi có cho đến nay:

<?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(); 
    } 
} 

và phương pháp điều khiển trông giống như:

<?php 

namespace App\Http\Controllers; 

use App\ListImport; 
use Illuminate\Http\Request; 

class ListImportController extends Controller 
{ 
public $model = ListImport::class; 

public function store(Request $request, ListImport $importList) 
{ 
    $request->file('importFile')->move(public_path('storage.crm.data'), $request->file('importFile')->getClientOriginalName()); 

    $importList->importFile = public_path('storage.crm.data') . '/' . $request->file('importFile')->getClientOriginalName(); 

    $importList->save(); 

} 
} 

Bất kỳ trợ giúp sẽ được đánh giá cao :)

+1

bên trong chức năng testCreate bạn có thể mô phỏng một tập tin csv như là một chuỗi thay vì bản thân không tải lên không? Tôi đã xử lý các tệp xml mà tôi đã tạo trên testcases của mình –

+1

Kiểm tra đơn vị 'store()' phải bao gồm nếu tệp được lưu trữ. Một thử nghiệm tốt hơn sẽ là 'assertStringEqualsFile()'. Đối số đầu tiên nên '$ importList-> importFile' và tham số thứ hai phải là' $ file'. Xét nghiệm này sẽ bao gồm nhiều hơn một tình trạng phản ứng. – user1965074

Trả lời

0

Có một phương pháp mới để thử nghiệm tải lên tệp trong Laravel. https://laravel-news.com/testing-file-uploads-with-laravel

Nó là như thế này: (từ các tài liệu)

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'); 
} 
Các vấn đề liên quan