phpunit 以及在框架中的使用

博客分类: software 阅读次数: comments

phpunit 以及在框架中的使用

phpunit 使用

自动化测试

PHPUnit

版本选择

主版本 PHP兼容性 下载地址
PHPUnit 9 PHP 7.3, PHP 7.4 http://phar.phpunit.cn/phpunit-9.phar
PHPUnit 8 PHP 7.2, PHP 7.3, PHP 7.4 http://phar.phpunit.cn/phpunit-8.phar
PHPUnit 7 PHP 7.1, PHP 7.2, PHP 7.3 http://phar.phpunit.cn/phpunit-7.phar
PHPUnit 6 PHP 7.0, PHP 7.1, PHP 7.2 http://phar.phpunit.cn/phpunit-6.phar
PHPUnit 5 PHP 5.6, PHP 7.0, PHP 7.1 http://phar.phpunit.cn/phpunit-5.phar
PHPUnit 4 PHP 5.3, PHP 5.4, PHP 5.5, PHP 5.6 http://phar.phpunit.cn/phpunit-4.phar

下载

➜ wget -O phpunit http://phar.phpunit.cn/phpunit-9.phar # 选择适合自己版本chmod +x phpunit
➜ sudo mv phpunit /usr/local/bin/phpunit
➜ phpunit --version

文档地址:http://www.phpunit.cn/manual/current/zh_cn/phpunit-book.html
参数说明:http://www.phpunit.cn/manual/current/zh_cn/phpunit-book.html#textui.clioptions
断言说明:http://www.phpunit.cn/manual/current/zh_cn/phpunit-book.html#appendixes.assertions
注解说明:http://www.phpunit.cn/manual/current/zh_cn/phpunit-book.html#appendixes.annotations

测试

代码

src/Email.php

<?php
declare(strict_types=1);

final class Email
{
    private $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 __toString(): 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
                )
            );
        }
    }
}

测试代码

tests/EmailTest.php

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

/**
 * @covers Email
 */
final class EmailTest extends TestCase
{
    public function testCanBeCreatedFromValidEmailAddress(): void
    {
        $this->assertInstanceOf(
            Email::class,
            Email::fromString('user@example.com')
        );
    }

    public function testCannotBeCreatedFromInvalidEmailAddress(): void
    {
        $this->expectException(InvalidArgumentException::class);

        Email::fromString('invalid');
    }

    public function testCanBeUsedAsString(): void
    {
        $this->assertEquals(
            'user@example.com',
            Email::fromString('user@example.com')
        );
    }
}

执行测试

➜ phpunit --bootstrap src/Email.php tests/EmailTest
PHPUnit 6.3.0 by Sebastian Bergmann and contributors.

...                                                                 3 / 3 (100%)

Time: 70 ms, Memory: 10.00MB

OK (3 tests, 3 assertions)

执行单元测试

➜ phpunit --bootstrap src/Email.php tests/EmailTest --filter=testCanBeCreatedFromValidEmailAddress
PHPUnit 6.5.3 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 75 ms, Memory: 10.00MB

OK (1 test, 1 assertion)

Hyperf自动化测试

定义规范

hyperf 常用测试命令

常用断言

自动化测试

hyperf 自动化测试文档地址:https://hyperf.wiki/2.0/#/zh-cn/testing

Hyperf 里测试默认通过 phpunit 来实现,但由于 Hyperf 是一个协程框架,所以默认的 phpunit 并不能很好的工作,因此我们提供了一个 co-phpunit 脚本来进行适配,您可直接调用脚本或者使用对应的 composer 命令来运行。自动化测试没有特定的组件,但是在 Hyperf 提供的骨架包里都会有对应实现。

composer require hyperf/testing # 安装命令

Bootstrap

Hyperf 提供了默认的 bootstrap.php 文件,它让用户在运行单元测试时,扫描并加载对应的库到内存里。

<?php

declare(strict_types=1);

error_reporting(E_ALL);
date_default_timezone_set('Asia/Shanghai');

! defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));
! defined('SWOOLE_HOOK_FLAGS') && define('SWOOLE_HOOK_FLAGS', SWOOLE_HOOK_ALL);

Swoole\Runtime::enableCoroutine(true);

require BASE_PATH . '/vendor/autoload.php';

Hyperf\Di\ClassLoader::init();

$container = require BASE_PATH . '/config/container.php';

$container->get(Hyperf\Contract\ApplicationInterface::class)

模拟 HTTP 请求

在开发接口时,我们通常需要一段自动化测试脚本来保证我们提供的接口按预期在运行,Hyperf 框架下提供了 Hyperf\Testing\Client 类,可以让您在不启动 Server 的情况下,模拟 HTTP 服务的请求:

<?php
use Hyperf\Testing\Client;

$client = make(Client::class);

$result = $client->get('/');

其他框架的自动化测试

lumen

lumen6.x 自动化测试文档地址:https://learnku.com/docs/lumen/6.x/testing/6119

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
>
    <testsuites>
        <testsuite name="Application Test Suite">
            <!-- <directory suffix="Test.php">./tests</directory> -->
            <directory suffix="Test.php">./app</directory>
        </testsuite>
    </testsuites>
    <php>
        <env name="LOGIN_USERNAME" value="********"/>
        <env name="LOGIN_PASSWORD" value="********"/>
    </php>
</phpunit>

文件:tests/TestCase.php

<?php
namespace LumenTest;

use Laravel\Lumen\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    /**
     * Creates the application.
     *
     * @return \Laravel\Lumen\Application
     */
    public function createApplication()
    {
        return require __DIR__.'/../bootstrap/app.php';
    }
}