oatllo

Write tests in PHP

Sure! Below are some examples of how to write tests in PHP using PHPUnit, one of the most popular testing frameworks for PHP. ### Installation of PHPUnit Make sure you have PHPUnit installed. You can do this via Composer: bash composer require --dev phpunit/phpunit ### Example Function to Test Let’s say you have a simple PHP function that adds two numbers together. We'll create a simple class for that: php // src/Calculator.php class Calculator { public function add($a, $b) { return $a + $b; } } ### Writing Tests Now, let's write tests for this Calculator class. Create a test class in a directory called tests (you may need to create it first): php // tests/CalculatorTest.php use PHPUnit\Framework\TestCase; class CalculatorTest extends TestCase { public function setUp(): void { $this->calculator = new Calculator(); } public function testAddPositiveNumbers() { $result = $this->calculator->add(2, 3); $this->assertEquals(5, $result); } public function testAddNegativeNumbers() { $result = $this->calculator->add(-2, -3); $this->assertEquals(-5, $result); } public function testAddZero() { $result = $this->calculator->add(0, 0); $this->assertEquals(0, $result); } } ### Running the Tests To run the tests, navigate to your project directory in the terminal and execute: bash vendor/bin/phpunit tests This will run all the tests inside the tests directory. ### Example of a More Complex Test Scenario Let’s say you want to test a method that calculates the factorial of a number. Here’s how you can implement that: php // src/MathHelper.php class MathHelper { public function factorial($n) { if ($n < 0) { throw new InvalidArgumentException("Negative numbers do not have factorials."); } return $n === 0 ? 1 : $n * $this->factorial($n - 1); } } ### Corresponding Tests You can create tests for the factorial function as follows: php // tests/MathHelperTest.php use PHPUnit\Framework\TestCase; class MathHelperTest extends TestCase { public function testFactorialOfPositiveNumber() { $mathHelper = new MathHelper(); $this->assertEquals(120, $mathHelper->factorial(5)); // 5! = 120 } public function testFactorialOfZero() { $mathHelper = new MathHelper(); $this->assertEquals(1, $mathHelper->factorial(0)); // 0! = 1 } public function testFactorialOfNegativeNumber() { $mathHelper = new MathHelper(); $this->expectException(InvalidArgumentException::class); $mathHelper->factorial(-1); } } ### Summary In this example, you learned how to write basic tests using PHPUnit for a simple calculator, and a more complex mathematical helper function. The structure involves setting up a test class that extends TestCase, defining test methods to execute your test cases, and using assertions provided by PHPUnit to verify your expected outcomes. Make sure to customize and expand your tests according to the functionalities of your application!

Articles: