Writing a simple PHPUnit test case involves the following steps:
Step 1: Install PHPUnit First, you need to install PHPUnit globally on your system using Composer. Run the following command in your terminal:
composer require --dev phpunit/phpunit
Step 2: Create a test file Create a new PHP file, e.g., "MyTest.php", and open it in a text editor.
Step 3: Import necessary classes Include the necessary classes at the top of your test file:
use PHPUnit\Framework\TestCase;
Step 4: Create a test class Create a new class that extends the TestCase class:
class MyTest extends TestCase
{
// ...
}
Step 5: Define test methods Write test methods within the test class. Each test method should start with the word "test":
public function testAddition()
{
$result = 2 + 2;
$this->assertEquals(4, $result);
}
public function testSubtraction()
{
$result = 5 - 3;
$this->assertEquals(2, $result);
}
Step 6: Run the test Save the test file and go to your terminal. Run the following command to execute your test:
phpunit MyTest.php
You should see the output indicating whether your tests passed or failed.
Note: The example above demonstrates simple assertions using the assertEquals method. There are many other assertion methods available in PHPUnit for different types of tests, such as assertTrue, assertFalse, assertArrayHasKey, etc. Make sure to explore the official PHPUnit documentation to learn more about the available assertion methods and additional features.