Write PHPUnit tests
Certainly! Below are examples of PHPUnit tests for a simple class that performs basic arithmetic operations. The class we will be testing is called Calculator, and it has methods for addition, subtraction, multiplication, and division.
### Calculator Class
Here's the implementation of the Calculator class:
php
calculator = new Calculator();
}
public function testAdd()
{
$this->assertEquals(5, $this->calculator->add(2, 3));
$this->assertEquals(0, $this->calculator->add(-2, 2));
$this->assertEquals(-1, $this->calculator->add(-2, 1));
}
public function testSubtract()
{
$this->assertEquals(-1, $this->calculator->subtract(2, 3));
$this->assertEquals(-4, $this->calculator->subtract(-2, 2));
$this->assertEquals(-1, $this->calculator->subtract(-2, -1));
}
public function testMultiply()
{
$this->assertEquals(6, $this->calculator->multiply(2, 3));
$this->assertEquals(0, $this->calculator->multiply(0, 2));
$this->assertEquals(-4, $this->calculator->multiply(-2, 2));
}
public function testDivide()
{
$this->assertEquals(2, $this->calculator->divide(6, 3));
$this->assertEquals(-1, $this->calculator->divide(-4, 4));
$this->assertEquals(0, $this->calculator->divide(0, 1));
}
public function testDivideByZero()
{
$this->expectException(InvalidArgumentException::class);
$this->calculator->divide(1, 0);
}
}
### Explanation of the Tests:
1. **testAdd()**: Verifies that the addition method returns the correct sum for various cases, including positive, negative, and zero.
2. **testSubtract()**: Checks if the subtraction method correctly calculates differences, including scenarios with negative inputs.
3. **testMultiply()**: Tests the multiplication method with positive, negative, and zero values to ensure it behaves correctly.
4. **testDivide()**: Ensures that division returns the expected results for various inputs, including dividing by zero.
5. **testDivideByZero()**: Confirms that attempting to divide by zero throws an InvalidArgumentException, as expected.
### Running the Tests
To run these tests, save the Calculator class in a file called Calculator.php and the test class in a file named CalculatorTest.php. Make sure you have PHPUnit installed and then run the following command in the terminal:
bash
phpunit CalculatorTest.php
If everything is set up correctly and the tests pass, you should see an output indicating that all tests were successful.