我正在使用 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()
函数中,但效果不佳。
最佳答案
从技术上讲,您还没有向您的应用程序发送请求,因此没有远程地址可供引用。事实上,这也是您的错误告诉我们的。
解决这个问题:
将行移到下面:
// Won't work, see comment below $crawler = $client->request('POST', '/category/new');
或者您可以编一个 IP 地址并用它进行测试。由于您仅使用 IP 来保存模型,因此同样有效。
就像评论中提到的@apokryfos,在测试用例中访问超全局被认为是不好的做法。因此,选项 2 可能是您的最佳选择。
关于php - 如何在 PHPUnit 测试用例中使用服务器变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588862/