简体   繁体   中英

$_SERVER['DOCUMENT_ROOT'] not recognised by php unit

I am writing a unit test for my code with phpunit. Code class has following:

<?

    // Dependencies
    //
    require_once($_SERVER['DOCUMENT_ROOT']."/includes/configs.php");

class xyz{
..
...
..
}
?>

Test Class is as follows:

<?php

require_once("xyz.php");

class testxyz extends PHPUnit_Framework_TestCase{

    public function setUp(){
        $this->xyz= new xyz();
    }

    public function testEmail(){

        $this->xyz->SetEmail('abc');
        $name = $this->xyz->GetEmail();
        $this->assertEquals($name == 'abc');
    }


}

When i run php unit on my test class, I get following error:

Fatal Error: Class xyz not found

This error got resolved by giving <?php instead of <? at the top of my code class.

Secondly, I get following error after first error was resolved:

Fatal error: require_once(): Failed opening required '/includes/configs.php'.

Which means $_SERVER['DOCUMENT_ROOT'] was not recognised by php unit.

Since code class can't be changed, how can I successfully run php unit without changing my code class. Please suggest any work around such that <? and $_SERVER['DOCUMENT_ROOT'] start working with php unit.

$_SERVER['DOCUMENT_ROOT'] relies on a specific environment. When you call PHPUnit it runs PHP without that environment.

Typically you want your code under test to be independent of the environment. A common setup is to have a bootstrapper that can bootstrap from a webserver-environment and a PHPUnit environment.

Rather that using $_SERVER['DOCUMENT_ROOT'] you can set the base directory in your bootstrapper by using the magic constants: __FILE__ and __DIR__ .

Similar to $_SERVER : $_GET , $_POST and $_COOKIE are also not available in a PHPUnit environment.

You can set $_SERVER['DOCUMENT_ROOT'] manually in your setUp method

public function setUp(){
    $_SERVER['DOCUMENT_ROOT'] = "...";
    $this->xyz= new xyz();
}

Reason of $_SERVER is not set: https://stackoverflow.com/a/2100577/1071156

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM