Unit testing with phpunit

Unit testing with phpunit

This tutorial assumes you are using PHP 8.1 or PHP 8.2. You'll learn how to write simple unit tests and how to download and run PHPUnit.

The documentation for PHPUnit 10 is here.

Download: You can use one of the following two methods:

1. PHP Archive (PHAR)

We distribute a PHP Archive (PHAR) that contains everything you need to use PHPUnit 10 . Just download it from here and make it executable:

wget -O phpunit https://phar.phpunit.de/phpunit-10.phar
➜ chmod +x phpunit
➜ ./phpunit --version
PHPUnit 10.0.0 by Sebastian Bergmann and contributors.

2.Composer

You can use Composer to add PHPUnit to your project as a local, per-project, development-time dependency:

➜ composer require --dev phpunit/phpunit ^10./vendor/bin/phpunit --version
PHPUnit 10.0.0 by Sebastian Bergmann and contributors.

The examples shown above assume composer is on your $PATH.

Your composer.json should look like this:

{
    
    
    "autoload": {
    
    
        "classmap": [
            "src/"
        ]
    },
    "require-dev": {
    
    
        "phpunit/phpunit": "^10"
    }
}

the code

src/Email.php

<?php 
declare(strict_types=1);
final class Email
{
    
    
    private string $email;
    private function __construct(string $email)
    {
    
    
        $this->ensureIsValidEmail($email);
        $this->email = $email;
    }
    public static function fromString(string $email): self
    {
    
    
        return new self($email);
    }
    public function asString(): string
    {
    
    
        return $this->email;
    }
    private function ensureIsValidEmail(string $email): void
    {
    
    
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    
    
            throw new InvalidArgumentException(
                sprintf(
                    '"%s" is not a valid email address',
                    $email
                )
            );
        }
    }
}

test code

tests/EmailTest.php

<?php 
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class EmailTest extends TestCase
{
    
    
    public function testCanBeCreatedFromValidEmail(): void
    {
    
    
        $string = '[email protected]';
        $email = Email::fromString($string);
        $this->assertSame($string, $email->asString());
    }
    public function testCannotBeCreatedFromInvalidEmail(): void
    {
    
    
        $this->expectException(InvalidArgumentException::class);
        Email::fromString('invalid');
    }
}

Test execution: either of the following two methods are available:

1. PHP Archive (PHAR)

./phpunit --bootstrap src/autoload.php tests
PHPUnit 10.0.0 by Sebastian Bergmann and contributors.
..                                        2 / 2 (100%)
Time: 70 ms, Memory: 10.00MB
OK (2 tests, 2 assertions)

The above assumes that you have downloaded phpunit.phar and put it in your $PATH as phpunit, and that src/autoload.php is a script that sets up autoloading for the class being tested. Such scripts are usually generated using tools such as phpab.

--bootstrap src/autoload.php instructs the PHPUnit command-line test runner to include src/autoload.php before running the tests.
tests instructs the PHPUnit command-line test runner to execute all tests declared in the *Test.php source code file in the tests directory .

2.Composer

./vendor/bin/phpunit tests
PHPUnit 10.0.0 by Sebastian Bergmann and contributors.
..                                        2 / 2 (100%)
Time: 70 ms, Memory: 10.00MB
OK (2 tests, 2 assertions)

The above assumes that vendor/autoload.php (the autoloader script managed by Composer) exists and is able to load the code for the Email class. Depending on how autoload is set up, you may need to run composer dump-autoload now.

tests instructs the PHPUnit command-line test runner to execute all tests declared in the Test.php source code file in the tests directory.

Some test components are recommended:

https://packagist.org/packages/mockery/mockery
phpunit/phpunit
fakerphp/faker
https://github.com/phpstan/phpstan
vimeo/psalm
mikey179/vfsstream
rector/rector

quote

declare和strict_types

ps:declare(strict_types=1);

Strict typing
By default, PHP will coerce values ​​of the wrong type to the scalar type expected by the function if it can. For example, if a parameter of a function is expected to be a string, but an integer is passed in, the final function will get a value of type string.
Strict mode can be enabled on a per-file basis. In strict mode, only a variable that exactly matches the type declaration will be accepted, otherwise a TypeError will be thrown. The only exception is that an integer can be passed to a function expecting a float.
Use the declare statement and strict_types statement to enable strict mode
https://blog.csdn.net/joshua317/article/details/121252625

assertsame

Use operators to check identity
Report errors identified by if if two variables have different types and values ​​or if two variables do not refer to the same object
https://docs.phpunit.de/en/10.1/assertions.html#assertsame

Guess you like

Origin blog.csdn.net/heshihu2019/article/details/132295983