Lecture Notes On Class 35:
Testing and Debugging PHP Code
Objective:
- Learn debugging techniques and tools for PHP.
- Introduction to unit testing with PHPUnit.
Outcome:
By the end of the class, students will be able to debug PHP code effectively and write unit tests using PHPUnit to ensure their code is functioning as expected.
1. Introduction to Debugging in PHP
Debugging is an essential skill for any developer. It helps identify and fix errors in the code and ensures that the application behaves as expected.
Types of Errors in PHP
- Syntax Errors: These occur when the code doesn't follow the correct syntax of PHP. Common errors include missing semicolons, unclosed parentheses, or incorrect keywords.
- Example:
php
Copy code
echo "Hello, world!" // Missing semicolon
- Runtime Errors: These errors occur while the script is running, usually due to bad input or logic errors.
- Example:
php
Copy code
echo $undefined_variable; // Runtime error (variable not defined)
- Logical Errors: These errors occur when the code runs without crashing but doesn't give the expected output.
- Example:
php
Copy code
$sum = 5 + 'abc'; // Logic error (not a valid addition operation)
- Fatal Errors: These are serious errors that stop the script from executing entirely, such as calling a non-existing function.
- Example:
php
Copy code
non_existing_function(); // Fatal error (function doesn't exist)
2. Debugging Techniques
2.1 Using var_dump() and print_r()
- var_dump(): Displays information about a variable, including its type and value.
- Example:
php
Copy code
$age = 25;
var_dump($age); // Output: int(25)
- print_r(): Displays a human-readable representation of a variable, especially useful for arrays or objects.
- Example:
php
Copy code
$arr = [1, 2, 3];
print_r($arr); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )
2.2 Using error_reporting() and ini_set()
- error_reporting(): This function controls which errors are reported by PHP.
- Example:
php
Copy code
error_reporting(E_ALL); // Report all errors
- ini_set(): It can be used to modify the PHP configuration, such as displaying errors.
- Example:
php
Copy code
ini_set('display_errors', 1); // Enable error display
2.3 Using Xdebug
Xdebug is a PHP extension that provides advanced debugging features such as breakpoints, stack traces, and profiling.
- Setting Up Xdebug: It can be installed and configured to work with popular IDEs like PHPStorm or Visual Studio Code.
- Key Features:
- Step through code execution.
- View variable values in real-time.
- Set breakpoints.
3. Introduction to Unit Testing in PHP with PHPUnit
Unit testing is the practice of testing individual parts of a program (units) to ensure they work as expected. PHPUnit is the most commonly used testing framework in PHP.
3.1 What is PHPUnit?
PHPUnit is a unit testing framework for PHP, which allows developers to write test cases for individual units of code, such as functions or methods, and then run these tests to verify that the code behaves as expected.
3.2 Setting Up PHPUnit
To start using PHPUnit in your PHP project, you'll need to install it.
- Install PHPUnit via Composer:
bash
Copy code
composer require --dev phpunit/phpunit
- Verify Installation:
bash
Copy code
./vendor/bin/phpunit --version
3.3 Writing Unit Tests with PHPUnit
- Basic Structure of a PHPUnit Test Case:
- A test class should extend PHPUnit\Framework\TestCase.
- Inside the class, each test method should be prefixed with test and contain assertions to check the expected results.
Example:
php
Copy code
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
public function testAdd()
{
$calc = new Calculator();
$result = $calc->add(2, 3);
$this->assertEquals(5, $result); // Check if 2 + 3 equals 5
}
public function testSubtract()
{
$calc = new Calculator();
$result = $calc->subtract(5, 3);
$this->assertEquals(2, $result); // Check if 5 - 3 equals 2
}
}
- Assertions: PHPUnit provides several assertion methods that you can use to check if the results of your code match the expected outcomes:
- assertEquals(): Checks if two values are equal.
- assertTrue(): Asserts that a condition is true.
- assertFalse(): Asserts that a condition is false.
- assertNull(): Asserts that a value is null.
- assertNotNull(): Asserts that a value is not null.
- assertContains(): Asserts that a value is contained in another value (like an array or string).
Example:
php
Copy code
$this->assertEquals('Hello', 'Hello'); // Passes because the strings are equal.
$this->assertTrue(1 < 2); // Passes because 1 is less than 2.
3.4 Running PHPUnit Tests
Once your test cases are written, you can run them using the PHPUnit command line tool.
- Run all tests:
bash
Copy code
./vendor/bin/phpunit
- Run a specific test case:
bash
Copy code
./vendor/bin/phpunit tests/CalculatorTest
- Test Output: PHPUnit will provide an output indicating whether the tests passed or failed, along with any errors or failures that occurred.
4. Debugging and Testing Workflow
To ensure high-quality code and smooth development, follow this workflow:
1. Write the code: Develop the functionality you want to implement.
2. Debug the code: Use debugging techniques such as var_dump(), error_reporting(), and Xdebug to identify and fix errors.
3. Write unit tests: Use PHPUnit to write test cases that ensure your code works as expected.
4. Run tests: Execute the test cases and confirm that all tests pass.
5. Refactor and improve: Based on the results of the tests, refactor the code and improve it where necessary.
5. Conclusion
By using PHP debugging techniques and unit testing with PHPUnit, you ensure your PHP applications are robust and reliable. Debugging helps in identifying issues in the code, while unit testing ensures that individual parts of the application function correctly. As you become more comfortable with these tools, you'll be able to write higher-quality, error-free code that is easier to maintain and scale.