Laravel API测试-如何测试具有外部API调用的API [英] Laravel API Test - How to test API that has external API call

查看:427
本文介绍了Laravel API测试-如何测试具有外部API调用的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的API代码

public function store (Request $request, $profileId)
{
    $all = $request->all();
    $token = AccessToken::with('users')->where('access_token',$request->input('access_token'))->first();

    if($token && $token->users->isOwnProfile($profileId))
    {
        $rules = [
            'access_token'     => 'required',
            'title'            => 'required',
            'description'      => 'required',
            'file_id'          => 'required',
            'audience_control' => 'required|in:' . join(',', PostRepository::$AUDIENCE_CONTROL),
            'tags'             => 'required',
        ];
        $validator = Validator::make($all, $rules);

        $error = $validator->errors()->toArray();
        if ($validator->fails())
        {
            return $this->setStatusCode(401)
                ->setStatusMessage(trans('api.validation failed'))
                ->respondValidationMessage($error);
        }
        try {
            $response = $this->postRepository->save($request, $profileId);
            if(isset($response['error']))
                return $this->messageSet([
                    'message' => $response['error']['message'],
                ], $response['error']['status_code']);

            return $this->setDataType('post_id')
                ->setStatusCode('200')
                ->respondWithCreatedId(trans('api.Post created'), $response->id);
        } catch (\Exception $e) {
            return $this->respondInternalError(trans('api.processing error'));
        }
    }
    return $this->respondInternalError('404 page');

}

从save方法调用另一个方法,该方法调用一个外部API.

From save method it calls another method that calls an external API.

/*
 * this function returns some response where it has profile_id for 
 * the file which in other save function is matched that the
 * profile_id passed as parameter is same with file profile_id
 */
public function getFileDetails($file_id)
{
    try
    {
        $response = json_decode((new Client())->request('GET', env('xyz','http://abc.xyz/api/v1').'/files/' . $file_id)->getBody()->getContents(), true);
    }
    catch (RequestException $e)
    {
        $response = json_decode($e->getResponse()->getBody()->getContents(), true);
    }

    return $response;

}

现在这是我对API的测试功能.

Now this is my test function for API.

public function testPostCreateChecksProfileMatchesCorrectly()
{
    $this->json('POST', 'profiles/' . $this->getProfile()->id . '/posts' . '?access_token=' . $this->getAccessToken(), [
        'title' => 'api testing title',
        'description' => 'api testing description',
        'audience_control' => 'public',
        'tags' => [
            'Animals',
            'City'
        ],
        'file_id' => '281'
    ])->seeJsonStructure([
        'success' => [
            'message',
            'post_id',
            'status',
        ],
    ]);
}

现在我的问题是如何为外部设备创建虚假响应 我正在测试的API.

我正在使用 PHPUnit & Laravel 5.2 .

I am using PHPUnit & Laravel 5.2.

推荐答案

首先,永远不要测试您不拥有的东西.外部API调用是您不拥有的一种想法.可能有一千个问题或用例可能出错,例如您提交数据,网络错误或其内部错误.在每种情况下,您都应该测试情况,这很乏味.而是使用moc对象,并对此有所期望.收听此播客, http://www.fullstackradio.com/37 这将帮助您清楚地理解

First of all never test a thing that you don't own. An external API call is a think that you don't own. There may a thousand of issue or use case that could be go wrong, like your submitting data, network error, or their internal error. Each of the case you should test the situation, which is tedious. Rather use a moc object and put some expectation on that. Listen to this podcast, http://www.fullstackradio.com/37 this will help you to understand clearly.

尝试将代码分成小块,然后分别测试每个块.您对单个测试的期望值过高.将您的验证逻辑放入FormRequest类中,将对您有很大帮助.

Try to break your code into small chunk and then test each chunk separately. You are expecting too much from a single test. put your validation logic in a FormRequest class, this will help you a lot.

这篇关于Laravel API测试-如何测试具有外部API调用的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆