【发布时间】:2014-12-20 18:24:25
【问题描述】:
我正在尝试对我的 Stripe webhook 处理程序的实现进行单元测试。 Stripe webhook 数据作为 POST 请求正文中的原始 JSON 通过网络传输,因此我捕获并解码数据:
public function store()
{
$input = @file_get_contents("php://input");
$request = json_decode($input);
return Json::encode($request);
}
我正在尝试对此代码进行单元测试,但我不知道如何在单元测试中发送原始 JSON 数据,以便我可以使用 file_get_contents("php:input//") 函数检索它。这是我尝试过的(使用PHPUnit):
protected $testRoute = 'api/stripe/webhook';
protected $validWebhookJson = <<<EOT
{
"id": "ch_14qE2r49NugaZ1RWEgerzmUI",
"object": "charge",
// and a bunch of other fields too
}
EOT;
public function testWebhookDecdoesJsonIntoObject()
{
$response = $this->call('POST', $this->testRoute, $this->validWebhookJson); // fails because `$parameters` must be an array
$response = $this->call('POST', $this->testRoute, [], [], ['CONTENT_TYPE' => 'application/json'], $this->validWebhookJson);
dd($response->getData(true)); // array(0) {} BOOOO!!! Where for to my data go?
}
我也尝试过curl,但这会发出一个外部请求,从单元测试的角度来看,这对我来说没有意义。如何模拟 POST 请求,其中包含我的 store 方法将拾取的正文中的原始 JSON 数据?
【问题讨论】:
-
第二次调用中的技术对我来说是正确的。我猜“一堆其他字段”的格式不正确,所以你基本上回显的 json 是空的。当然,截断示例中的尾随逗号不是有效的 json。我将从 xdebugging store() 开始。
标签: php unit-testing