Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phpMick's avatar
Level 15

Fake JSON data for testing.

Hi,

At the moment, I have this in one of my tests:

$data = "[[{'start_date':'2018-01-01','end_date':'2018-02-01','thing':'12'}],
                    [{'start_date':'2018-03-01','end_date':'2018-04-01','thing':'8'}]]";

Basically I just need a couple of dates and a small random number, then converted to JSON for a post.

Should I just be using faker to do this, inside the test. or is there a better way?

Mick

0 likes
5 replies
burlresearch's avatar

You don't really need Faker for this,

$data = json_encode([
    'start_date' => Carbon::yesterday()->toDateString(),
    'end_date' =>  Carbon::now()->toDateString(),
    'thing' => rand(11,99),
]);
phpMick's avatar
Level 15

Yes, but I want the dates to be random. I also want a few different rows.

Cinek's avatar

Simple example to generate random date between 1970-01-01 and now:

$now = time();
$date = Carbon::createFromTimestamp($now - rand(1,$now))->toDateString();
burlresearch's avatar

Faker does make this easier, of course. It's a simple matter to type-hint it in the constructor of your test case, then you can use it, if that's what you want to do.

    /**
     * @var Generator
     */
    private $faker;

    /**
     * ExampleTest constructor.
     */
    public function __construct(Generator $faker)
    {
        $this->faker = $faker;
    }

Please or to participate in this conversation.