php - 流明/Laravel : Can't figure out how unittesting a json response works

标签 php laravel unit-testing lumen

我不知道单元测试是如何工作的。

我有一个返回 JSON 响应的 Controller

Controller.php

public function getDiscount(Request $request)
{
    if (isset($request) && !empty($request)) {
        return response()->json($this->discount->calculateDiscount($request->json()->all()))->getOriginalContent();
    }
}

对于 postman ,这是这条路线的结果:

客户发布:

{
  "customer-id": "3",
  "items": [
    {
      "product-id": "A101",
      "quantity": "2",
      "unit-price": "9.75",
      "total": "19.50"
    },
    {
      "product-id": "A102",
      "quantity": "1",
      "unit-price": "49.50",
      "total": "49.50"
    }
  ],
  "total": "69.00"
}

API 响应

{
    "applied_discounts": [
        {
            "id": 3,
            "name": "Tools Discount",
            "description": "Seems like you really like Tools, here's one for free!"
        }
    ],
    "discounted_items": [
        {
            "product-id": "A101",
            "quantity": "2",
            "unit-price": "9.75",
            "total": "19.50",
            "discounted_price": 15.6
        }
    ],
    "discounted_price": 65.1,
    "original_price": "69.00"
}

现在当我尝试进行单元测试时,这就是我想出的:

public function testToolsDiscount()
{
    $this->json('POST', '/discount',
        [
            'customer-id' => '3',
            'items' => [
                [
                    'product-id' => 'A101',
                    'quantity' => '2',
                    'unit-price' => '9.75',
                    'total' => '19.50'
                ],
                [
                'product-id' => 'A102',
                'quantity' => '1',
                'unit-price' => '49.50',
                'total' => '49.50'
                ]
            ],
            'total' => '69.00'
        ])
        ->seeJson(
            [
            'applied_discounts' => [
                [
                    'id' => 3,
                ]
            ],
        ]);
}

但是当我运行它时,这是我得到的错误

DiscountTest::testToolsDiscount Invalid JSON was returned from the route. Perhaps an exception was thrown?

我做错了什么?

最佳答案

确保您的路线匹配指定的 '/discount' 及其可能具有的任何前缀。

关于php - 流明/Laravel : Can't figure out how unittesting a json response works,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51293530/

相关文章:

.net 4.0 代码契约(Contract)。什么时候使用?他们什么时候浪费时间了?

PHP/Zend Framework 2 - 无法在动态生成的表中显示表字段值

php - Laravel:使用在 WAMP 中创建的数据库

php - Laravel - Composer 在更新平台后检测到问题

c# - xUnit.NET 有什么好的文档/书籍/教程吗?

ios - OCMock stub block

php - MySQL + PHP——用户身份验证级别

php - 如何获取选项标签的完整值?

php - 如何修复 stripe-php 没有这样的 payment_method 错误

Laravel - 重定向到路由 POST