easyswoole 单元测试 php单元测试
安装
composer require easyswoole/phpunit
Tip: 自3.2.5版本的Easyswoole起,已经默认集成了 easyswoole/phpunit 组件
目录结构
|--App
|--|--|
.....
|--Tests
|--|--Api
|--|--|--IndexTests.php
|--|--Models
|--|--|--UserTests.php
IndexTests.php API接口测试
<?php
namespace Tests\Api;
use PHPUnit\Framework\TestCase;
use App\HttpController\Index;
use EasySwoole\HttpClient\HttpClient;
class IndexTests extends TestCase
{
protected $baseUrl = 'http://ip地址:9501';
public function testIndex()
{
$url = $this->baseUrl . '/user/login';
$client = new HttpClient($url);
$username = 'zhangshan';
$password = 'qwe12345';
$deviceId = 1;
$client->setQuery(['username' => $username, 'password' => $password, 'device_type' => $deviceId]);
$response = $client->get();
$body = $this->parsingJson($response->getBody());
if ($response->getBody()) {
var_dump($body);
} else {
echo 'Error: ' . $response->getErrCode() . ': ' . $response->getErrMsg() . "\n";
}
$this->assertTrue(true);//断言结果是否为true,如果不为true则报错
$this->assertEquals('hello world', $response->response);//断言结果是否等于hello world,如果不等于则报错
}
/**
* 解析json数据
*
* @param string $jsonStr
* @return object
*/
protected function parsingJson($jsonStr)
{
// $body = json_decode($jsonStr);
return json_decode($jsonStr);
}
}
UserTests.php 数据模型测试
<?php
namespace Tests\Models;
use PHPUnit\Framework\TestCase;
use App\Models\AccountModel;
class UserTests extends TestCase
{
public function testInfo()
{
$uid = 13;
$accountModel = new AccountModel();
$data= $accountModel->info($uid);
// var_dump($data); 8
$this->assertEquals(8, $data['robot_id']);//断言返回的id为1
}
}