自动化测试

    1. "scripts": {
    2. "test": "./test/co-phpunit -c phpunit.xml --colors=always"
    3. },

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

    1. <?php
    2. declare(strict_types=1);
    3. error_reporting(E_ALL);
    4. ! defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));
    5. \Swoole\Runtime::enableCoroutine(true);
    6. require BASE_PATH . '/vendor/autoload.php';
    7. require BASE_PATH . '/config/container.php';
    1. <?php
    2. use Hyperf\Testing\Client;
    3. $client = make(Client::class);
    4. $result = $client->get('/');

    因为 Hyperf 支持多端口配置,除了验证默认的端口接口外,如果验证其他端口的接口呢?

    1. <?php
    2. use Hyperf\Testing\Client;
    3. $client = make(Client::class,['server' => 'adminHttp']);
    4. $result = $client->json('/user/0',[
    5. 'nickname' => 'Hyperf'
    6. ]);

    让我们写个小 DEMO 来测试一下。

    接下来,我来介绍如何通过配合 testing,来快速调试代码,顺便完成单元测试。

    假设我们在 UserDao 中实现了一个查询用户信息的函数

    1. namespace App\Service\Dao;
    2. use App\Constants\ErrorCode;
    3. use App\Exception\BusinessException;
    4. use App\Model\User;
    5. class UserDao extends Dao
    6. {
    7. /**
    8. * @param $id
    9. * @param bool $throw
    10. * @return
    11. public function first($id, $throw = true)
    12. $model = User::query()->find($id);
    13. if ($throw && empty($model)) {
    14. throw new BusinessException(ErrorCode::USRE_NOT_EXIST);
    15. }
    16. return $model;
    17. }
    18. }
    1. namespace HyperfTest\Cases;
    2. use HyperfTest\HttpTestCase;
    3. use App\Service\Dao\UserDao;
    4. /**
    5. * @internal
    6. * @coversNothing
    7. */
    8. class UserTest extends HttpTestCase
    9. {
    10. public function testUserDaoFirst()
    11. {
    12. $model = \Hyperf\Utils\ApplicationContext::getContainer()->get(UserDao::class)->first(1);
    13. var_dump($model);
    14. $this->assertSame(1, $model->id);

    然后执行我们的单测