1

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.

clint
  • 1,786
  • 4
  • 34
  • 60

2 Answers2

2

$_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.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

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

Community
  • 1
  • 1
Farid Movsumov
  • 12,350
  • 8
  • 71
  • 97