【问题标题】:Symfony 3.4 - How to mock Request object for PHPUnit Test of ServiceSymfony 3.4 - 如何为 PHPUnit 服务测试模拟 Request 对象
【发布时间】:2019-12-21 06:56:33
【问题描述】:

我有一项服务需要为其编写 phpunit 测试

这个服务有一个方法接受来自 JSON POST 的 Symfony\Component\HttpFoundation\Request 对象

我需要以某种方式使用 JSON POST 模拟 Request 对象,以便我可以正确测试此方法

Service 方法如下所示

namespace AppBundle\Service;

use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class SubscriptionNotificationProcessor
 * @package AppBundle\Service
 */
class SubscriptionNotificationProcessor
{
     ...
     public function process(Request $request)
     {
           $parameterBag = $request->request;
           $notification_type = $parameterBag->get('notification_type');
           ...
      }
 }

我的问题是,如何模拟填充 JSON 数据的请求参数?

【问题讨论】:

  • 据我所知,您不需要模拟 Request 对象,您可以创建自己的请求实例并调用您的服务
  • 如果我只是创建自己的实例,如何获取 JSON 数据?
  • 为什么不直接模拟呢? gianarb.it/blog/symfony-unit-test-controller-with-phpunit 请注意,通常不值得对控制器操作进行单元测试。您可以对操作可能使用的任何自定义服务进行单元测试,但通常需要对其进行功能测试。

标签: unit-testing symfony phpunit symfony-3.4


【解决方案1】:

这是Symfony\Component\HttpFoundation\Request的构造函数

public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
    {
        $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
    }

您可以看到$resquest 是第二个参数,您可以这样做:

$request = new Request([], [json_encode([ 'foo' => 'bar'])], [], [], [], [], []);

现在您可以将对象传递给您的服务process($request);

【讨论】:

  • 第二个参数不是 Symfony\Component\HttpFoundation\ParameterBag 的实例吗?
  • HttpFoundation 组件将通过构造函数中的函数 initialize 来重建 $request。第二个参数是一个数组,但是当您进行 $request->request 时,您得到了另一个重建变量,该实例是 Symfony\Component\HttpFoundation\ParameterBag
猜你喜欢
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 2013-11-12
  • 2019-08-04
  • 2019-04-13
  • 2012-03-26
相关资源
最近更新 更多