【问题标题】:Get $_GET parameters in unit testing Symfony2在单元测试 Symfony2 中获取 $_GET 参数
【发布时间】:2014-12-19 11:56:48
【问题描述】:

我是测试新手。我想测试我的服务和功能,但这会得到 $_GET 参数。如何在测试中模拟获取参数?

【问题讨论】:

    标签: php unit-testing symfony testing phpunit


    【解决方案1】:

    使用 Symfony2 时,您应该将代码从直接使用 PHP 超全局变量中抽象出来。而是将 Request 对象传递给您的服务:

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

    然后,在您的单元测试中,执行以下操作:

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

    您还可以考虑使您的服务更加通用,并在调用它的方法时传递您想要的值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 2018-12-14
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      相关资源
      最近更新 更多