PHP Lumen - TDD test Image upload does not work in PHP’s Lumen framework

Asked

Viewed 83 times

0

I’m trying to create a test method for uploading images using the PHP framework (Lumen). However I am having problems with the following Uploadedfile method: $request->file('images') it always returns me a value null. below the code:

public function testCreate() // função teste, executado com phpunit
{
    $token = $this->tokenGenerate();

    Storage::fake('products');

    factory(App\ProductImage::class)->make();
    $productImage = factory(\App\ProductImage::class)->create()->toArray();
    $this->seeInDatabase('product_images', $productImage);

    $file = new File(UploadedFile::fake()->create('image.jpg')); // aqui é onde está sendo criado um objeto do tipo UploadedFile e é enviado por post pela rota abaixo

    $this->post('/api/productImages', ['product_id' => $productImage['product_id'], 'images'=>$file], ['Authorization' => $token['access_token'], 'Content-Type' => 'multpart\formdata']);
    dd(json_decode($this->response->content()));
}

and this is my controller:

public function store(Request $request)
{
    $product_id = $request->product_id;
    $file = $request->file('images'); // não reconhece como file 'eu acho'

    dd($file); // sempre retorna null

    $fileName = $file->hashName();
    $url = $file->store('products');

}

2 answers

0

I think your mistake is setting the header Content-Type:

Instead: 'Content-Type' => 'multpart\formdata'

Try it this way: 'Content-Type' => 'multipart/form-data'

0


Actually, I needed to use the call to as a request to send an object of the type UploadedFile

$file = UploadedFile::fake()->image('avatar.jpg');

factory(App\ProductImage::class)->make();
$productImage = factory(\App\ProductImage::class)->create()->toArray();
$this->seeInDatabase('product_images', $productImage);

$server = ['HTTP_AUTHORIZATION' => 'Bearer ' . $token['access_token']];
$this->call(
    'POST',
    '/api/productImages', 
    ['product_id' => $productImage['product_id']], 
    [], 
    ['images' => $file], $server)
->json();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.