【发布时间】: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