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

标签 php symfony phpunit

我正在使用 PHPUnit 测试用例测试模块。所有的东西都工作正常,但是当我使用 $_SERVER['REMOTE_ADDR'] 时,它会出现 fatal error 并停止执行。

CategoryControllerTest.php

<?php
namespace ProductBundle\Controller\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
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('ProductBundle\Controller\CategoryController::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());
    }
}

错误

有 1 个错误:

1) ProductBundle\Tests\Controller\CategoryControllerTest::testCategory Undefined index: REMOTE_ADDR

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

最佳答案

从技术上讲,您还没有向您的应用程序发送请求,因此没有远程地址可供引用。事实上,这也是您的错误告诉我们的。

解决这个问题:

  1. 将行移到下面:

    // Won't work, see comment below    
    $crawler = $client->request('POST', '/category/new');
    
  2. 或者您可以编一个 IP 地址并用它进行测试。由于您仅使用 IP 来保存模型,因此同样有效。

就像评论中提到的@apokryfos,在测试用例中访问超全局被认为是不好的做法。因此,选项 2 可能是您的最佳选择。

关于php - 如何在 PHPUnit 测试用例中使用服务器变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588862/

相关文章:

php - 跨站点请求伪造 (CSRF) 缓解

javascript - PHP 序列化失败并以半序列化格式存储

php - socket_create_listen 不适用于 Windows 中的所有接口(interface)

symfony - 如何在 Symfony 2 中获取当前包?

symfony 3 : how to add role to specific user

多次测试后 phpunit 失败

php - 如何获取请求 Tor 网页的客户端 IP?

symfony2 bundle 更新程序

PHP 单元测试错误 - PHPUnit_Util_DeprecatedFeature_Logger

php - mock 对象参数验证问题