How to use fixtures in PHPUnit?

Member

by denis , in category: PHP General , 9 months ago

How to use fixtures in PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 9 months ago

@denis 

To use fixtures in PHPUnit, follow these steps:


Step 1: Install PHPUnit

  • Install PHPUnit by running the following command in your terminal:
1
composer require --dev phpunit/phpunit


Step 2: Create a Fixture class

  • Create a new class file for your fixture, for example, UserFixture.php.
  • In this class, create a method that will insert or prepare the data you want to use in your tests. For example:
1
2
3
4
5
6
7
class UserFixture
{
    public static function loadUsers()
    {
        // Insert or prepare users data here
    }
}


Step 3: Load the fixture in your test class

  • In your test class, add a setUp method where you load the fixture data. For example:
1
2
3
4
5
6
7
8
9
class MyTest extends PHPUnitFrameworkTestCase
{
    protected function setUp(): void
    {
        UserFixture::loadUsers();
    }
    
    // Your test methods go here
}


Step 4: Run your tests

  • Run your tests using the phpunit command in your terminal:
1
./vendor/bin/phpunit


PHPUnit will now load the fixture data before running each test method in your test class.