我正在使用PHPUnit測試用例測試模塊。所有的事情工作正常,但當我使用$_SERVER['REMOTE_ADDR']
它給出了致命的錯誤,並停止執行。如何在PHPUnit測試用例中使用服務器變量?
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()
功能,但它不工作,以及。
,如果你想使你的應用程序更容易測試你不應該直接訪問'$ _SERVER'或其他超全局獲取IP地址。爲他們創建容器,然後在測試時嘲笑它們。 – apokryfos