我正在创建一个功能测试,我需要模拟从Guzzle发出的请求到外部API的响应。我如何嘲笑此请求?我发现了一些模拟请求本身的示例,但是我想模拟另一个请求中的请求。
示例:
我有控制器:
use GuzzleHttp\Client;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
class MyController extends Controller
{
public function indexAction(Request $request)
{
$response = Client()->post('http://some.url', [
'form_params' => [
'param1' => 'value1'
]
]);
$result = $this->doSomethingWithTheResponse($response);
return new JsonResponse(['status' => $result], Response::HTTP_OK);
}
}
我有一个测试班:
class MyTestClass extends WebTestCase
{
public function testSomething()
{
$client = static::createClient();
$client->request('GET', 'path_to_my_controller');
$response = json_decode($client->getResponse()->getContent());
$this->assertEquals($response, $expectedResponse);
}
}
我该如何模拟控制器内部的耗时请求,而仍在测试类中使用$client->request()
?