如何在 PHPUnit 测试用例中使用服务器变量?

2022-01-25 00:00:00 php symfony phpunit

我正在使用 PHPUnit 测试用例测试模块.一切正常,但是当我使用 $_SERVER['REMOTE_ADDR'] 时,它会出现致命错误并停止执行.

CategoryControllerTest.php

boot();$this->container = static::$kernel->getContainer();$this->em = static::$kernel->getContainer()->get('doctrine')->getManager();}公共功能 testCategory() {$ip_address = $_SERVER['REMOTE_ADDR'];$client = 静态::createClient(array(), array('HTTP_HOST' => static::$kernel->getContainer()->getParameter('test_http_host')));$crawler = $client->request('POST', '/category/new');$client->enableProfiler();$this->assertEquals('ProductBundleControllerCategoryController::addAction', $client->getRequest()->attributes->get('_controller'));$form = $crawler->selectButton('new_category')->form();$form['category[name]'] = "电子";$form['category[id]'] = "美国版";$form['category[ip]'] = $ip_address;$client->submit($form);$this->assertTrue($client->getResponse()->isRedirect('/category/new'));//检查重定向是否正确$client->followRedirect();$this->assertEquals(1, $crawler->filter('html:contains("类别创建成功.")')->count());}}

错误

有 1 个错误:

<块引用>

1) ProductBundleTestsControllerCategoryControllerTest::testCategory未定义索引:REMOTE_ADDR

我尝试将它添加到 setUp() 函数中,但效果不佳.

解决方案

创建返回IP地址的服务,并在测试用例中模拟该服务.

在这里,将控制器和服务创建为 UserIpAddress.get() 将返回用户的 ip 地址.

service.yml

UserIpAddress:类:AppBundleControllerUserIpAddressController论据:容器:@service_container"

UserIpAddressController.php

类 UserIpAddressController{公共函数获取(){返回 $_SERVER['REMOTE_ADDR'];}}

<块引用>

创建UserIpAddress"服务的模拟.它将覆盖现有服务.使用UserIpAddress"服务获取项目中的 IP 地址.

CategoryControllerTest.php

$UserIpAddress = $this->getMockBuilder('UserIpAddress')->disableOriginalConstructor()->getMock();$UserIpAddress->expects($this->once())->方法('get')->willReturn('192.161.1.1');//设置你想使用的IP地址

现在,使用 $UserIpAddress->get();

获取 IP 地址

I am testing modules using PHPUnit Test cases. All the things working fine but when i use $_SERVER['REMOTE_ADDR'] it gives fatal error and stops execution.

CategoryControllerTest.php

<?php
namespace ProductBundleControllerTestsController;
use SymfonyBundleFrameworkBundleTestWebTestCase;
class CategoryControllerTest extends WebTestCase {

     protected function setUp() {
        static::$kernel = static::createKernel();
        static::$kernel->boot();
        $this->container = static::$kernel->getContainer();
        $this->em = static::$kernel->getContainer()->get('doctrine')->getManager();
    }

    public function testCategory() {
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $client = static::createClient(
          array(), array('HTTP_HOST' => static::$kernel->getContainer()->getParameter('test_http_host')
        ));

        $crawler = $client->request('POST', '/category/new');
        $client->enableProfiler();

        $this->assertEquals('ProductBundleControllerCategoryController::addAction', $client->getRequest()->attributes->get('_controller'));
        $form = $crawler->selectButton('new_category')->form();
        $form['category[name]'] = "Electronics";
        $form['category[id]']   = "For US";
        $form['category[ip]']   = $ip_address;
        $client->submit($form);

        $this->assertTrue($client->getResponse()->isRedirect('/category/new')); // check if redirecting properly
        $client->followRedirect();
        $this->assertEquals(1, $crawler->filter('html:contains("Category Created Successfully.")')->count());
    }
}

Error

There was 1 error:

1) ProductBundleTestsControllerCategoryControllerTest::testCategory Undefined index: REMOTE_ADDR

I have tried to add it in setUp() function but it's not working as well.

解决方案

Create service which returns ip address and mock the service in test case.

Here, create controller and service as UserIpAddress. get() will return ip address of user.

service.yml

UserIpAddress:
    class: AppBundleControllerUserIpAddressController
    arguments: 
    container: "@service_container"  

UserIpAddressController.php

class UserIpAddressController
{
  public function get()
  {
    return $_SERVER['REMOTE_ADDR'];
  }
}

Create mock of "UserIpAddress" service. It will override existing service. Use 'UserIpAddress' service to get ip address in your project.

CategoryControllerTest.php

$UserIpAddress = $this->getMockBuilder('UserIpAddress')
    ->disableOriginalConstructor()
    ->getMock();

$UserIpAddress->expects($this->once())
  ->method('get')
  ->willReturn('192.161.1.1'); // Set ip address whatever you want to use

Now, get ip address using $UserIpAddress->get();

相关文章