How to Test PHP Code With phpUnit?

Testing PHP code is a critical aspect of software development, ensuring that applications function as intended and maintain their integrity over time. PHPUnit stands out as a premier testing framework for PHP, empowering developers to create comprehensive test suites and validate their code effectively. This article serves as a thorough guide to leveraging PHPUnit for testing PHP code.

Installing PHPUnit

PHPUnit is a popular testing framework for PHP that facilitates unit testing, integration testing, and functional testing. To install PHPUnit, you can use Composer, a dependency manager for PHP projects. Here’s how you can install PHPUnit using Composer:

composer require --dev phpunit/phpunit

Once installed, PHPUnit becomes available for testing PHP code in your project.

These are the following ways to test the PHP code:

Table of Content

  • Unit Testing
  • Integration Testing
  • Functional Testing

Unit Testing

Unit testing involves isolating and testing individual units or components of code. Developers focus on testing functions, methods, or classes independently to verify their correctness and functionality. Unit testing involves testing individual units or components of code in isolation. In PHPUnit, you define test methods within a test class that extends PHPUnit\Framework\TestCase. Use assertions like assertEquals, assertTrue, assertFalse, etc., to validate expected behavior.

Example: This example shows the validation test of email.

PHP
<?php
class EmailValidator {
    public function isValidEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
}
PHP
<?php
require_once 'EmailValidator.php'; // Include the EmailValidator class file

use PHPUnit\Framework\TestCase;

class EmailValidatorTest extends TestCase {
    public function testValidEmail() {
        $validator = new EmailValidator();
        $result = $validator->isValidEmail('test@example.com');
        $this->assertTrue($result);
    }
}

Output:

Integration Testing

Integration testing assesses the interactions between various components or modules of the application. This approach ensures that different parts of the system work harmoniously when integrated, detecting any compatibility or communication issues. Integration testing checks interactions between components or modules to ensure they work together correctly. You can use mock objects to simulate external dependencies. Use getMockBuilder or createMock to create mocks.

Example: This example shows the Integration Testing.

PHP
<?php
require_once 'PaymentGateway.php';
require_once 'PaymentProcessor.php'; 

use PHPUnit\Framework\TestCase;

class PaymentProcessingIntegrationTest extends TestCase {
    public function testPaymentProcessingSuccess() {
        $mockGateway = $this->createMock
                      (PaymentGateway::class);
        $mockGateway->method('processPayment')
            ->willReturn(true);

        $processor = new PaymentProcessor($mockGateway);
        $processed = $processor->processPayment(100.00,
                                                'visa');
        $this->assertTrue($processed);
    }

    public function testPaymentProcessingFailure() {
        $mockGateway = $this->createMock 
                      (PaymentGateway::class);
        $mockGateway->method('processPayment')
            ->willReturn(false);

        $processor = new PaymentProcessor($mockGateway);
        $processed = $processor->processPayment(50.00, 'amex');
        $this->assertFalse($processed); 
    }
}
PHP
<?
class PaymentProcessor {
    protected $gateway;

    public function __construct(PaymentGateway $gateway) {
        $this->gateway = $gateway;
    }

    public function processPayment($amount, $cardType) {
        return $this->gateway->processPayment($amount,
                                              $cardType);
    }
}
PHP
<?
class PaymentGateway {
    public function processPayment($amount, $cardType) {
        // Simulate payment processing logic
        if ($amount > 0 && in_array($cardType, ['visa',
                                              'mastercard'])) {
            return true;
        } else {
            return false;
        }
    }
}

Output:

Functional Testing

Functional testing evaluates the application’s behavior from an end-user perspective. It tests the system’s functionality against specific requirements, simulating user interactions to validate that the application performs as expected. Functional testing evaluates the entire system’s functionality from the end-user perspective. Test user interactions and expected outcomes. Use assertions to validate system behavior.

Example: This example shows the Functional Testing.

PHP
<?php
require_once 'FileProcessor.php'; 

use PHPUnit\Framework\TestCase;

class FileProcessorFunctionalTest extends TestCase {
    public function testFileProcessing() {
        $processor = new FileProcessor();
        $processed = $processor->processFile('test.txt');
        $this->assertTrue($processed);
    }
}
PHP
<?
class FileProcessor {
    public function processFile($filename) {
        // Simulate file processing logic
        return file_exists($filename);
    }
}

Output:

Note: “Vendor/bin/phpunit TestFileName” will be used to run the test.

Conclusion

Testing PHP code with PHPUnit is a fundamental practice for maintaining code quality and reliability. By embracing unit testing, integration testing, and functional testing, developers can identify and address issues early in the development lifecycle, fostering robust and resilient applications. With its intuitive syntax and versatile features, PHPUnit empowers developers to build comprehensive test suites that instill confidence in their PHP codebases.