Handling Large Payload for testing API

2 years ago

lloricode

https://lloricode.com/blog/handling-large-payload-for-testing-api

Code

<?php

namespace Tests\Factories;

use Illuminate\Testing\TestResponse;

use function Pest\Laravel\post;

final class MySubmitPayloadTestFactory
{
    // this is better, when dealing with Model
    private string $firstName;
    private string $lastName;

    /** @var array<string> */
    private array $hobbies = [];

    /** @var array<array<string, string|int>> */
    private array $product = [];

    private function __construct()
    {
    }

    public static function make(): self
    {
        return new self();
    }

    public function firstName(string $firstName): self
    {
        $this->firstName = $firstName;
        return $this;
    }

    public function lastName(string $lastName): self
    {
        $this->lastName = $lastName;
        return $this;
    }

    public function addHobbies(string $hobby): self
    {
        $this->hobbies[] = $hobby;
        return $this;
    }

    public function addProduct(string $product, int $quantity = 1): self
    {
        $this->product[] = [
            'id' => $product,
            'quantity' => $quantity,
        ];
        return $this;
    }

    public function runPost(): TestResponse
    {
        return post(route('submit'), $this->generatePayload());
    }

    private function generatePayload(): array
    {
        return [
            'first_name' => $this->firstName,
            'last_name' => $this->lastName,
            'hobbies' => $this->hobbies,
            'products' => $this->product,
        ];
    }
}

Output

HELO: Local email testing for your desktop!