# 单元测试

HerosphpApp中默认内置了phpunit单元测试组件。

# 安装

composer require --dev phpunit/phpunit

在根目录phpunit.xml,默认已经配置好了,当然您是可以改变配置

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="./boot.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <coverage processUncoveredFiles="true">
        <include>
            <directory suffix=".php">./app/services</directory>
        </include>
    </coverage>
    <testsuites>
        <testsuite name="Tests">
            <directory suffix="Test.php">./test/services</directory>
        </testsuite>
    </testsuites>
</phpunit>

# 使用

新建文件test/UserServiceTest.php,用于测试服务

<?php
namespace test\service;

use app\service\UserService;
use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase
{

    public function testAdd()
    {
        $service = new UserService();
        $this->assertEquals(3,$service->add(1,2),'add errors');
    }
}

# 运行

项目根目录里运行

composer test

结果类似如下:

> vendor/bin/phpunit
PHPUnit 9.5.25

..                                                                  2 / 2 (100%)

Time: 00:00.003, Memory: 6.00 MB

OK (2 tests, 2 assertions)

上次更新: 10/27/2022, 11:18:25 AM