簡體   English   中英

如何在PHPUnit測試用例中使用服務器變量?

[英]How to use server variables in PHPUnit Test cases?

我正在使用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());
    }
}

錯誤

有1個錯誤:

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

我試圖在setUp()函數中添加它,但它不能正常工作。

從技術上講,您還沒有向您的應用程序發送請求,因此沒有遠程地址可供參考。 事實上,這也是你的錯誤告訴我們的。

要解決這個問題:

  1. 將線移到下面:

     // Won't work, see comment below $crawler = $client->request('POST', '/category/new'); 
  2. 或者您可以組成一個IP地址並進行測試。 由於您只使用IP來保存模型,因此也可以。

與評論中提到的@apokryfos一樣,在測試用例中訪問超全局也被認為是不好的做法。 所以選項2可能是你最好的選擇。

創建返回ip地址並在測試用例中模擬服務的服務。

在這里,創建控制器和服務作為UserIpAddress get()將返回用戶的ip地址。

service.yml

UserIpAddress:
    class: AppBundle\Controller\UserIpAddressController
    arguments: 
    container: "@service_container"  

UserIpAddressController.php

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

創建“UserIpAddress”服務的模擬。 它將覆蓋現有服務。 使用“UserIpAddress”服務獲取項目中的IP地址。

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

現在,使用$UserIpAddress->get();獲取ip地址

您可以創建另一個類,它將返回服務器var然后模擬它。

或者,您可以將服務器var直接設置/取消設置到測試用例中。 用PHPUnit 6.2.2做了:

 /**
 * Return true if the user agent matches a robot agent
 */
public function testShouldReturnTrueIfRobot()
{
    $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';

    $this->configMock->method('getRobotUserAgents')
        ->willReturn('bot|crawl|slurp|spider|mediapartner');

    $test = $this->robotTest->isBot();

    static::assertTrue($test);
}

/**
 * Test return false if no user agent
 */
public function testShouldReturnFalseIfNoAgentUser()
{
    unset($_SERVER['HTTP_USER_AGENT']);

    $test = $this->robotTest->isBot();

    static::assertFalse($test);
}

測試方法是:

 /**
 * Detect if current user agent matches a robot user agent
 *
 * @return bool
 */
public function isBot(): bool
{
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        return false;
    }

    $userAgents = $this->config->getRobotUserAgents();
    $pattern = '/' . $userAgents . '/i';

    return \preg_match($pattern, $_SERVER['HTTP_USER_AGENT']);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM