关于laravel的单元测试记录-----控制器部分

关于laravel的单元测试记录-----控制器部分


测试laravel 的控制器层会涉及到Requst对象,故而得构造Request,尝试两种解决方案。

解决方案
  • 模拟http请求
  • 构造Request
实现
  • 模拟http请求
    该方法需要运行http服务。
    /**
     * 封装公共请求方法
     * @param $method
     * @param $url
     * @param $options
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function my_http($method, $url, $options) {
        //设置请求头
        $headers           = [
            'Accept'     => 'application/json',
            'Grant-Type' => 'authorization_code'
        ];
        $config['headers'] = $headers;
        //请求创建对象
        $http     = new Client($config);
        $response = $http->request($method, "http://xxx/api/{$url}", $options);
        return $response;
    }

	/**
	*测试
	*/
    public function testStats() {
        $options['query'] = [
            'timeFrame' => 'WEEK',
            'createdAt' => '2020-05-01;2020-05-31'
        ];
        $response         = $this->my_http('GET', "orders/stats", $options);
        $this->assertEquals('200', $response->getStatusCode());
    }
  • 构造Request块
    无需运行http服务,具体的 Request::create也可自己再封装一层;
    public function testStore() {
    	//数据
        $options = [
        ];
        //查看 Request::create底层代码发现 request请求头需要以HTTP_前缀打头。
        $headers = [
            'HTTP_ACCEPT'     => 'application/json',
            'HTTP_Grant-Type' => 'authorization_code',
            'SERVER_PORT'     => 8000,
      ];
        $request = Request::create('/orders', 'POST', $options, [], [], $headers);
        $response    = $this->controller()->store($request);
        $this->assertEquals('200', $response->getStatusCode());
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值