我有一个我想测试的 API 端点,它接收一个 POST 负载。端点基本上调用 Omnipay Sage Pay处理服务器通知的库。
我可以使用 Postman 客户端 POST 到这个端点,但是当使用 Laravel phpunit 测试时,例如
$response = $this->post($url, $data);
Omnipay库看不到帖子数据?
我认为这是因为 Laravel 助手 $this->post
不使用 application/x-www-form-urlencoded POST 请求?我查看了 $this->post
的幕后情况,它似乎直接调用了 Controller /方法,这很有意义..
我最接近这项工作的是直接使用 Guzzle(见下文),但是这会将请求路由到“测试” session 之外并返回到我假设的本地应用程序?这会中断我的测试,因为我在 POST 调用之前通过工厂设置了一些测试数据。
$response = $client->request('POST', $url, ['form_params' => $data]);
我不太确定问题出在哪里,是在我的测试中还是在 Omnipay 库本身?
最佳答案
解决了。事实证明,Omnipay 允许您在调用 Omnipay 对象时将自己的 Request 类/对象作为第三个参数传递。然后,该库将可以访问测试 $this->post($url, $data);
调用中的 POST 参数。
Laravel 的 Illuminate\Http\Request
是 Symfony\Component\HttpFoundation\Request
的扩展,所以我们可以直接通过它。
<?php
use Illuminate\Http\Request;
class SagePayController extends Controller
{
protected $gateway;
protected function setupGateway(Request $request)
{
$this->gateway = OmniPay::create('SagePay\Server', null, $request);
...
}
...
关于Laravel 测试 API 端点 - 缺少 POST 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57730546/