Home > Article > Backend Development > Unit testing of PHP function parameter types
By using PHPUnit and @dataProvider annotations, you can unit test the parameter types of PHP functions: Create a test class. Use @dataProvider to provide different types of data. In the test method, use assertType() to assert the parameter type.
Unit testing of PHP function parameter types
Unit testing is the process of verifying that a function or method works as expected. In PHP, you can use the PHPUnit library for unit testing.
Using PHPUnit unit testing function parameter types
class MyFunctionTest extends \PHPUnit\Framework\TestCase { public function testTypeHint() { // ... } }
@dataProvider
annotation to provide type-hinted test data: /** * @dataProvider typeHintProvider */ public function testTypeHint() { // ... } public function typeHintProvider() { return [ ['int', 1], ['string', 'foo'], ['array', []], ]; }
$this->assertType( )
Assert the type of parameter: public function testTypeHint() { $this->assertType($hint, $arg); }
Practical case
Consider the following function:
function sum(int $a, int $b) { return $a + $b; }
Corresponding unit test:
class SumTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider typeHintProvider */ public function testTypeHint($hint, $arg) { $this->assertType($hint, $arg); } public function typeHintProvider() { return [ ['int', 1], ['int', '1'], // 失败,'1' 不是 int 类型 ['string', 'foo'], ['array', []], ]; } }
By running this unit test, you can verify that the parameter types of function sum
are checked as expected.
The above is the detailed content of Unit testing of PHP function parameter types. For more information, please follow other related articles on the PHP Chinese website!