Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variables are null when using PHPUnit

Tags:

php

phpunit

I am putting PHPUnit testing into an existing project. Global constants variables are used extensively. In my unit test functions are failing because the global variables are null. Here is an example of a failing test

static $secret_key = "a secret Key";
class secret_key_Test extends PHPUnit_Framework_TestCase
{
    function test_secret_key()
    {
        global $secret_key; 
        $this->assertEquals($secret_key, "a secret Key");   
    }
}

>> Failed asserting that 'a secret Key' matches expected null

Any help would be greatly appreciated

Update: I have tried removing static and adding

protected $backupGlobals = FALSE;

To the class declaration without success.

like image 244
rp90 Avatar asked Jan 31 '12 01:01

rp90


People also ask

What is the use of PHPUnit?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit architecture for unit testing frameworks that originated with SUnit and became popular with JUnit.

Is PHPUnit a framework?

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. The currently supported versions are PHPUnit 9 and PHPUnit 8.

Is PHPUnit open source?

#3) PHPUnitIt is an open source testing tool used for PHP code. It is the most widely used framework for unit testing.


2 Answers

This answer doesn't work. I asked a virtually identical question here and wound up with an answer that makes more sense; you can't overwrite the protected property $backupGlobals in the test Class that PHPUnit will see. If you're running on the command line, it seems that you can get Globals to work by creating an xml configuration file and setting up backupGlobals to false there.

EDIT: You need to declare $secret_key both global and assign a value to it in the global space when using PHPUnit. PHP defaults to placing globally initialized variables into the global namespace, but PHPUnit changes this default when backing up globals!

The following changes need to happen:

global $secret_key; // Declaring variable global in global namespace
$secret_key = "a secret Key"; // Assigning value to global variable

Your code should work now.

like image 151
Malovich Avatar answered Sep 18 '22 13:09

Malovich


You should ask phpunit not to backup globals

protected $backupGlobals = FALSE;

like it is said in the original article from S. Bergmann: https://web.archive.org/web/20130407024122/http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html

like image 26
zerkms Avatar answered Sep 20 '22 13:09

zerkms