【发布时间】:2022-01-19 00:36:00
【问题描述】:
我对 Slim 4 完全陌生,但我成功地创建了一个项目并编写了 API 端点来进行一些计算。
这是一个POST 路由,它需要一个 JSON 负载。在 Postman 中,我将 POST 发送到 http://localhost:8089/api/discounts/calculate,其中:
{
"order": {
"id": "1",
"customer-id": "1",
"items": [
{
"product-id": "B102",
"quantity": "10",
"unit-price": "4.99",
"total": "49.90"
}
],
"total": "49.90"
},
"discount_strategy": "overall_percentage_from_total"
}
在回复中我得到HTTP 200 OK,这是我所期望的。一切正常,但在 PHPUnit 中不行。
我想为此端点创建一个测试,所以我创建了扩展 TestCase 的新测试类,它可以访问这个受保护的方法:https://github.com/slimphp/Slim-Skeleton/blob/master/tests/TestCase.php#L71
所以我写了:
public function testOrder1AgainstOverallPercentageFromTotal()
{
$app = $this->getAppInstance();
$payload = [
'order' => [
'id' => 1,
'customer-id' => 1,
'items' => [
'product-id' => 'B102',
'quantity' => '10',
'unit-price' => '4.99',
'total' => '49.90',
],
'total' => '49.90',
],
'discount_strategy' => 'overall_percentage_from_total',
];
$req = $this->createRequest('POST', '/api/discounts/calculate');
$request = $req->withParsedBody($payload);
$response = $app->handle($request);
//var_dump($response->getBody()->getContents()); die;
$this->assertEquals(200, $response->getStatusCode());
}
但它总是给我 HTTP 400 说:
格式错误的 JSON 输入
当我转储 getBody() 或 getContents() 时,我得到一个空心对象或空字符串作为内容。
There was 1 failure:
1) Tests\Functional\CalculateDiscountsActionTest::testOrder1AgainstOverallPercentageFromTotal
Failed asserting that 400 matches expected 200.
我做错了什么?
我的计算逻辑位于扩展App\Application\Actions\Action 的Action 类中,我可以访问我在Postman 中发送的有效负载:$input = $this->getFormData();。这是stdClass,但足以让我抓住输入并完成工作。
为什么 PHPUnit 看不到我的有效载荷?
【问题讨论】: