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

Jan*_*nvi 5 php phpunit symfony

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

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

错误

有1个错误:

1)ProductBundle \ Tests \ Controller \ CategoryControllerTest :: testCategory未定义的索引:REMOTE_ADDR

我试图将其添加到setUp()功能中,但效果不佳。

Loe*_*oek 1

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

要解决此问题:

  1. 将行移动到下面:

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

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