我的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');
}
保存方法调用另一个方法,该方法调用外部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编写的测试函数。
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。