Using Data Providers in PHPUnit Tests
This is the before code, where a single test is run, and each scenario I’m testing could be influenced by the previous scenario (not a good thing, unless that was my goal, which it was not).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * Tests the getRegistrationsWithinNumDays function. */ public function testGetRegistrationsWithinNumDays() { $firstRegDateTimeStr = '2024-03-18 08:00:00'; $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-18 09:00:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-19 13:00:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-20 14:20:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-20 17:35:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-21 17:35:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-22 08:00:00']); $registrations = Utils::getIdsOfRegistrationsWithinNumDays(1, $firstRegDateTimeStr); $this->assertEquals(2, count($registrations)); $registrations = Utils::getIdsOfRegistrationsWithinNumDays(2, $firstRegDateTimeStr); $this->assertEquals(3, count($registrations)); $registrations = Utils::getIdsOfRegistrationsWithinNumDays(3, $firstRegDateTimeStr); $this->assertEquals(5, count($registrations)); } |
This is the after code, where three tests are run. Unfortunately this takes 3x longer to execute. The upside is that each scenario cannot affect the others and it’s perhaps more readable and easier to add additional scenarios.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Data provider for testGetRegistrationsWithinNumDays. */ public function registrationsDataProvider() { return [ // Label => [numDays, expectedCount]. '1 day' => [1, 2], '2 days' => [2, 3], '3 days' => [3, 5], ]; } /** * Tests the getRegistrationsWithinNumDays function using a data provider. * * @dataProvider registrationsDataProvider */ public function testGetRegistrationsWithinNumDays($numDays, $expectedCount) { $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-18 08:00:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-19 09:00:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-20 13:00:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-21 14:20:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-21 17:35:00']); $this->mhpreregTestHelpers->createRegistration(['field_reg_datetime' => '2024-03-22 17:35:00']); $registrations = Utils::getIdsOfRegistrationsWithinNumDays($numDays, '2024-03-18 08:00:00'); $this->assertEquals($expectedCount, count($registrations), "Failed for {$numDays} days."); } |