我想在laravel中测试HTTP路由。 URL的动作函数调用帮助程序函数,该函数调用外部API。在测试过程中如何模拟外部API调用?
public function actionFunction(){
$helper = new HelperClassHelper();
return Response::json($helper->getNames());
}
在这里,getNames()函数进行了外部API调用。我该如何模拟呢?
答案 0 :(得分:1)
您可以在操作中将HelperClassHelper添加为依赖项,然后可以在测试中对其进行模拟:
public function actionFunction(HelperClassHelper $helper){
return Response::json($helper->getNames());
}
在测试中:
$this->app->bind(HelperClassHelper::class, function () { /* return mock */ });
答案 1 :(得分:0)
让我这么简单。
遵循此步骤:
1。)添加服务/srv
。在这种情况下,我使用的是邮递员api。
app/Services/MyService/HttpClient.php
2。)添加控制器namespace App\Services\MyService;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
class HttpClient
{
public function send(array $payload) : Response
{
return app(Client::class)
->request('POST', 'https://postman-echo.com/post', $payload);
}
}
app/Http/Controllers/TestController.php
3。)添加测试文件namespace App\Http\Controllers;
use App\Services\MyService\HttpClient;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class TestController extends Controller
{
public function index(Request $request)
{
$response = app(HttpClient::class)->send($request->toArray());
$data = json_decode( $response->getBody()->getContents(),true);
return response()->json(
$data,
$response->getStatusCode()
);
}
}
tests/Feature/SampleTest.php
4。)添加json文件namespace Tests\Feature;
use App\Services\MyService\HttpClient;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
class SampleTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
//do awesome thing
}
public function testExample()
{
$this->mock(HttpClient::class, function ($mock) {
return $mock->shouldReceive('send')
->once()
->andReturn(new Response(
$status = 200,
$headers = [],
File::get(base_path('tests/files/success.json'))
));
});
$data = [
'mock' => 'no'
];
$response = $this->call('post','/test', $data);
$response->assertExactJson(['mock' => 'yes']);
$response->assertStatus(200);
}
}
以获得虚假响应:
tests/files/success.json