How can PHP scripts be tested to ensure proper functionality?
PHP scripts can be tested to ensure proper functionality by using unit testing frameworks such as PHPUnit. These frameworks allow developers to write test cases that verify the expected behavior of their code. By writing comprehensive test cases that cover different scenarios, developers can ensure that their PHP scripts work as intended.
// Example PHP script to demonstrate unit testing using PHPUnit
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
// PHPUnit test case for the Calculator class
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
public function testAdd() {
$calculator = new Calculator();
$this->assertEquals(5, $calculator->add(2, 3));
$this->assertEquals(10, $calculator->add(5, 5));
$this->assertEquals(0, $calculator->add(-5, 5));
}
}
// Run the PHPUnit tests
// Assuming PHPUnit is installed globally
// Run the following command in the terminal: phpunit CalculatorTest.php