简体   繁体   English

在单元测试Symfony2中获取$ _GET参数

[英]Get $_GET parameters in unit testing Symfony2

I am new in testing. 我是测试新手。 I want to test my service and function, but this gets $_GET parameter. 我想测试我的服务和功能,但是得到$ _GET参数。 How I can simulate get parameter in test? 如何在测试中模拟get参数?

When using Symfony2, you should abstract your code away from direct usage of PHP superglobals. 使用Symfony2时,应使代码远离直接使用PHP超全局变量的抽象。 Instead pass a Request object to your service: 而是将Request对象传递给您的服务:

use Symfony\Component\HttpFoundation\Request;

class MyService
{
    public function doSomething(Request $request)
    {
        $foo = $request->query->get('foo');
        // ...
    }
}

Then, in your unit tests, do something like: 然后,在单元测试中,执行以下操作:

use Symfony\Component\HttpFoundation\Request;

class MyServiceTest
{
    public function testSomething()
    {
        $service = new MyService();
        $request = new Request(array('foo' => 'bar'));
        $service->doSomething($request);
        // ...
    }
}

You could also consider making your service even more generic, and just pass the values you want when calling it's methods: 您还可以考虑使服务更加通用,并在调用其方法时传递所需的值:

class MyService
{
    public function doSomething($foo)
    {
        // ...
    }
}

$service = new MyService();
$service->doSomething($request->query->get('foo');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM