MiguelStevens's avatar

Method for reusing test data?

I have the following tests

public function testReturnsDifferenceInRows()
    {
        $eventDate = factory(EventDate::class)->create([
            'id' => 3,
            'date_from' => Carbon::now(),
            'date_until' => Carbon::now()->addDay(5),
            'time_from' => '08:00',
            'time_until' => '08:00'
        ]);

        $this->assertEquals(6, $eventDate->recurring->count());
    }

    public function testReturnsDifferenceInRowsOverlapUntilTime()
    {
        $eventDate = factory(EventDate::class)->create([
            'id' => 3,
            'date_from' => Carbon::now(),
            'date_until' => Carbon::now()->addDay(5),
            'time_from' => '08:00',
            'time_until' => '02:00'
        ]);

        $this->assertEquals(6, $eventDate->recurring->count());
    }

    public function testReturnsDifferenceInRowsOverlapMidnight()
    {
        $eventDate = factory(EventDate::class)->create([
            'id' => 3,
            'date_from' => Carbon::now(),
            'date_until' => Carbon::now()->addDay(5),
            'time_from' => '23:00',
            'time_until' => '02:00'
        ]);

        $this->assertEquals(6, $eventDate->recurring->count());
    }

As you can see I use almost exactly the same data, the only variables here are the time_from and time_until.

How can I rewrite this as to reuse the other data?

0 likes
3 replies
MiguelStevens's avatar

The data providers don't really fit this case, since I'm only using one dataset per test. The method that returns data is the best solution for now, thanks

mikenewbuild's avatar

In your example the assertions are all the same, so you could also compact them into a single test and use a data provider. It's actually a good use case for a data provider.

However, I personally prefer the solution with the local method and multiple tests unless I'm dealing with dozens of cases.

Please mark answer correct to help others find the solution - thanks.

Please or to participate in this conversation.