laravel – 如何在不同情况下测试和模拟guzzle响应?

我想测试我的API控制器使用来自其他服务的一些guzzle请求.
我有一个请求下载链接.

>这是我的API路线

Route::group(['prefix' => '/v1'],function () {
Route::get('/exampledl','DownloadController@downloadChecker');
});

> DownloadChecker控制器检查用户是管理员还是订户向其他域上的某个服务发出guzzle请求,如果没有向另一个服务执行另一个Guzzle请求,并且每种情况的响应都不同.这是控制器检查管理员角色的一部分.

$client = new Client();
try {
    $response = $client->request('GET','https://www.example.com/api/user?u=' . $request->uid);
    $json = \GuzzleHttp\json_decode($response->getBody()->getContents(),True);

    // if user doesn't exist in CM

    //this part has been written to avoid repeating code
    if (array_key_exists('user',$json) && $json['user'] == null) {
        abort(403);
    }
    elseif (in_array("administrator",$json['Roles'])) {
        User::create([
            'uid'               => (int)$request->uid,'subscription.role' => 'administrator',]);
        $client = new Client();
$response = $client->request('GET',"https://vod.example2.com/vod/2.0/videos/{$a_id}?secure_ip={$u_ip}",[
    'headers' => [
        'authorization' => '**********'
    ]
]);
$json = \GuzzleHttp\json_decode($response->getBody()->getContents(),TRUE);

if (isset($json['data']['mp4_videos'])) {
    $links = [];
    foreach ($json['data']['mp4_videos'] as $mp_video) {
        if (stripos($mp_video,"h_144") !== false) {
            $links['144p'] = $mp_video;
        }
        elseif (stripos($mp_video,"h_240") !== false) {
            $links['240p'] = $mp_video;
        }
        elseif (stripos($mp_video,"h_360") !== false) {
            $links['360p'] = $mp_video;
        }
        elseif (stripos($mp_video,"h_480") !== false) {
            $links['480p'] = $mp_video;
        }
        elseif (stripos($mp_video,"h_720") !== false) {
            $links['720p'] = $mp_video;
        }
        elseif (stripos($mp_video,"h_1080") !== false) {
            $links['1080p'] = $mp_video;
        }
    }
    }

>我的一个测试.

public function test_user_notExist_admin()
{
$client = new Client();
$response = $client->request('GET','https://www.example.com/api/user_days_and_roles?u=' . request()->uid);
$json = \GuzzleHttp\json_decode($response->getBody()->getContents(),True);

$this->get('/api/v1/exampledl?uid=1&n_id=400&u_ip=104.58.1.45&dl_id=a81498a9')
    ->assertStatus(200)
    ->assertSee('links');

$this->assertDatabaseHas('users',[
    'uid'               => (int)request('uid'),]);
}

还有一些其他条件检查,我不知道如何模拟这些不同的情况.

我应该为每种情况进行单元测试吗?或者有没有办法让测试环境中的guzzle返回自定义响应?还是其他任何方式?

解决方法

另一种逐个模拟函数的方法:

$mock = Mockery::mock(DownloadController::class)->makePartial();
     $mock->shouldReceive('et_download_links_from_download_server')->andReturn('123465');
       $this->app->instance(DownloadController::class,$mock);

相关文章

laravel的dd函数不生效怎么办
看不懂laravel文档咋办
安装laravel框架出现command怎么办
Laravel开发API怎么使用事务
laravel怎么构建复杂查询条件
laravel如何实现防止被下载