自动化测试
"scripts": {
"test": "./test/co-phpunit -c phpunit.xml --colors=always"
},
Hyperf 提供了默认的 bootstrap.php
文件,它让用户在运行单元测试时,扫描并加载对应的库到内存里。
<?php
declare(strict_types=1);
error_reporting(E_ALL);
! defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));
\Swoole\Runtime::enableCoroutine(true);
require BASE_PATH . '/vendor/autoload.php';
require BASE_PATH . '/config/container.php';
<?php
use Hyperf\Testing\Client;
$client = make(Client::class);
$result = $client->get('/');
因为 Hyperf 支持多端口配置,除了验证默认的端口接口外,如果验证其他端口的接口呢?
<?php
use Hyperf\Testing\Client;
$client = make(Client::class,['server' => 'adminHttp']);
$result = $client->json('/user/0',[
'nickname' => 'Hyperf'
]);
让我们写个小 DEMO 来测试一下。
接下来,我来介绍如何通过配合 testing
,来快速调试代码,顺便完成单元测试。
假设我们在 UserDao
中实现了一个查询用户信息的函数
namespace App\Service\Dao;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\User;
class UserDao extends Dao
{
/**
* @param $id
* @param bool $throw
* @return
public function first($id, $throw = true)
$model = User::query()->find($id);
if ($throw && empty($model)) {
throw new BusinessException(ErrorCode::USRE_NOT_EXIST);
}
return $model;
}
}
namespace HyperfTest\Cases;
use HyperfTest\HttpTestCase;
use App\Service\Dao\UserDao;
/**
* @internal
* @coversNothing
*/
class UserTest extends HttpTestCase
{
public function testUserDaoFirst()
{
$model = \Hyperf\Utils\ApplicationContext::getContainer()->get(UserDao::class)->first(1);
var_dump($model);
$this->assertSame(1, $model->id);
然后执行我们的单测