Skip to content

Latest commit

 

History

History
85 lines (55 loc) · 2.25 KB

GlobalVariables.md

File metadata and controls

85 lines (55 loc) · 2.25 KB

Managing Global Variables

In situations where apps store data in global variables (e.g. $GLOBALS) the GlobalVariables trait creates fixtures to safely manipulate these variables and reset them between tests.

Methods

setGlobalVariable()

Set the value of a global variable for the duration of the test.

setGlobalVariable(string $key, mixed $value = null): self

This method will directly alter the $GLOBALS superglobal, then restore the original value at the conclusion of the test method.

Parameters

$key
The global variable name.
$value
The value to set for the global variable.
Passing null will effectively unset() the global variable.

Return values

This method will return the calling class, enabling multiple methods to be chained.


deleteGlobalVariable()

Delete an existing global variable for the duration of the test.

deleteGlobalVariable(string $key): self

This method is an alias of setGlobalVariable($key, null);

Parameters

$key
The global variable name.

Return values

This method will return the calling class, enabling multiple methods to be chained.

Examples

Overwriting existing global variables

Imagine we have a global $db object, which represents our database. If we wish to replace the database with a mock, the code to do so might look like this:

use App\Database;
use App\PostList;
use AssertWell\PHPUnitGlobalState\GlobalVariables;
use PHPUnit\Framework\TestCase;

class MyTestClass extends TestCase
{
    use GlobalVariables;

    /**
     * @test
     */
    public function fetchLatestPosts_is_empty_if_there_are_no_posts()
    {
        $db = $this->createMock(Database::class);
        $db->expects($this->once())
            ->method('getRow')
            ->willReturn([]);

        $this->setGlobalVariable('db', $db);

        $this->assertEmpty((new PostList)->fetchLatestPosts());
    }
}

Regardless of whether or not fetchLatestPosts_is_empty_if_there_are_no_posts() passes, the $db global variable will be reset after the test method completes.