在单元测试中发起对项目的接口请求,应该怎么操作呢?

= - =

希望能在单元测试中直接发起对接口的请求,并断言接口返回的数据是否正确。这个应该怎么操作呢?

1965 2 4
2个回答

菜徐坤

我是 弄了个请求的函数
/**

  • 发送http请求
  • @param $url
  • @param array|null $data
  • @param string $method
  • @param string[] $header
  • @param bool $https
  • @param int $timeout
  • @return bool|string
    */
    function curl_request(
    string $url,
    string $method = 'get',
    array $data = [],
    array $header = array("content-type: application/json"),
    bool $https = true,
    int $timeout = 5)
    {
    $method = strtoupper($method);
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容,但不输出
    if ($https) {
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
    }
    if ($method != "GET") {
    if ($method == 'POST') {
    curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
    }
    if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
    $result = curl_exec($ch);//执行请求
    curl_close($ch);//关闭curl,释放资源
    return $result;
    }

然后这样使用的 不知道 符不符合你的预期
截图

  • 暂无评论
ifui

我的是参考源码写了个简单的启用方法,可以参考一下,由于绕过了一些东西(部分源码还没理解透),可能会出现部分问题,所以放出来和大家相互讨论

<?php

namespace Ifui\WebmanMarket\Testing\Traits;

use FastRoute\Dispatcher;
use support\Request;
use Webman\Config;
use Webman\Http\Response;
use Webman\Route;
use function get_class;
use function is_array;

trait MakeHttpRequest
{

    /**
     * Additional headers for the request.
     *
     * @var array
     */
    protected $defaultHeaders = [];

    /**
     * Additional cookies for the request.
     *
     * @var array
     */
    protected $defaultCookies = [];

    /**
     * Add an authorization token for the request.
     *
     * @param string $token
     * @param string $type
     * @return $this
     */
    public function withToken(string $token, string $type = 'Bearer')
    {
        return $this->withHeader('Authorization', $type . ' ' . $token);
    }

    /**
     * Add a header to be sent with the request.
     *
     * @param string $name
     * @param string $value
     * @return $this
     */
    public function withHeader(string $name, string $value)
    {
        $this->defaultHeaders[$name] = $value;

        return $this;
    }

    /**
     * Flush all the configured headers.
     *
     * @return $this
     */
    public function flushHeaders()
    {
        $this->defaultHeaders = [];

        return $this;
    }

    /**
     * Visit the given URI with a GET request.
     *
     * @param string $uri
     * @param array $parameters
     * @param array $headers
     * @return Response
     */
    public function get($uri, $parameters = [], $headers = [])
    {
        $this->withHeaders($headers);
        return $this->call('GET', $uri, $parameters);
    }

    /**
     * Define additional headers to be sent with the request.
     *
     * @param array $headers
     * @return $this
     */
    public function withHeaders(array $headers)
    {
        $this->defaultHeaders = array_merge($this->defaultHeaders, $headers);

        return $this;
    }

    /**
     * Call the given URI and return the Response.
     *
     * @param string $method
     * @param string $uri
     * @param array $parameters
     * @return Response
     */
    protected function call($method, $uri, $parameters = [])
    {
        $ret = Route::dispatch($method, $uri);

        if ($ret[0] === Dispatcher::FOUND) {
            $request = $this->request($method, $uri, $parameters);
            $callback = $ret[1]['callback'];
            $route = $ret[1]['route'];
            $route = clone $route;
            $args = !empty($ret[2]) ? $ret[2] : null;
            if ($args) {
                $route->setParams($args);
            }
            if (is_array($callback) && isset($callback[0]) && $controller = get_class($callback[0])) {
                /** @var Response $res */
                return call_user_func([new $controller, $callback[1]], $request, $args);
            }
        } else {
            return new Response(404, [], '404');
        }
    }

    /**
     * Mock send request.
     *
     * @param $method
     * @param $uri
     * @param $parameters
     * @return mixed
     */
    public function request($method, $uri, $parameters = [])
    {
        $requestClassName = Config::get('app.request_class', Request::class);
        $request = new $requestClassName('');
        $request->_data = [
            'post' => $parameters,
            'get' => $parameters,
            'headers' => $this->defaultHeaders,
            'cookie' => $this->defaultCookies,
            'files' => [], // TODO
            'method' => $method,
            'protocolVersion' => '1.1',
            'host' => 'localhost',
            'uri' => $uri,
        ];
        return $request;
    }

    /**
     * Visit the given URI with a GET request, expecting a JSON response.
     *
     * @param string $uri
     * @param array $headers
     * @return Response
     */
    public function getJson($uri, $parameters = [], $headers = [])
    {
        return $this->json('GET', $uri, $parameters, $headers);
    }

    /**
     * Call the given URI with a JSON request.
     *
     * @param string $method
     * @param string $uri
     * @param array $data
     * @param array $headers
     * @return Response
     */
    public function json($method, $uri, $data = [], $headers = [])
    {
        $content = json_encode($data);

        $this->withHeaders([
            'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
            'CONTENT_TYPE' => 'application/json',
            'Accept' => 'application/json',
        ]);

        $rsp = $this->call($method, $uri, $data);
        $body = $rsp->rawBody();
        $json = json_decode($body, true) ?? $body;
        $rsp->withBody($json);
        return $rsp;
    }
}

这里是使用示例:

<?php

namespace market\apple\tests\unit;

use market\apple\tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testIndex()
    {
        $default_timezone = config('app.default_timezone');
        $this->assertIsString($default_timezone);

        $rsp = $this->get('/apple/index/index');
        $this->assertSame(200, $rsp->getStatusCode());
        $this->assertSame('hello webman market', $rsp->rawBody());

        $rsp = $this->getJson('/apple/index/json');
        $this->assertArrayHasKey('code', $rsp->rawBody());
    }
}
  • 暂无评论
年代过于久远,无法发表回答
×
🔝