WebTestCase Phpunit发送原始数据不起作用

psy*_*o66 8 phpunit file-get-contents raw-data

我尝试在PhpUnit中的WebTestCase中发送原始数据,但它不起作用:

$jsonEvent = '{
      "type": "invoice.payment_succeeded",
}';
$this->client->request(
    'POST',
    '/api/v1/stripe/webhook',
    [],
    [],
    ['CONTENT_TYPE' => 'application/json'],
    $jsonEvent
);
Run Code Online (Sandbox Code Playgroud)

我尝试获取这样的数据:

$input = file_get_contents("php://input");
var_dump($input);
Run Code Online (Sandbox Code Playgroud)

但是$input空的

不确定但是也许不可能在webtestcase中获得类似的内容输入?

提前致谢.

Jan*_*tis 4

我假设您正在使用SymfonyWebTestCase。如果是这种情况,那么首先,从 json 中删除无效的逗号:

$jsonEvent = '{
  "type": "invoice.payment_succeeded"
}';
Run Code Online (Sandbox Code Playgroud)

其次,我假设您以这种方式创建客户端:

$this->client = static::createClient();
Run Code Online (Sandbox Code Playgroud)

如果是这种情况,那么问题是request方法不是执行 http request,而是查找控制器和操作(内部使用"Symfony\Component\HttpKernel\Controller\ControllerResolver")并调用它传递参数,在请求方法中将内容和标头设置为适当的 symfony 对象。

这就是你不能使用的原因:

$input = file_get_contents("php://input");
Run Code Online (Sandbox Code Playgroud)

因为您实际上正在运行相同的脚本。

要将帖子正文纳入您的操作中,一种方法是:

public function myAction(Request $request)
{
    $input = $request->getContent();
Run Code Online (Sandbox Code Playgroud)

参考文献和示例

  1. Symfony 与客户合作
  2. Symfony 客户端错误