Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fake $_SERVER variables in phpUnit

Tags:

php

phpunit

I'm still new to phpUnit and I can't make my (very simple) test work.

<?php

use PHPUnit\Framework\TestCase;

class userTest extends TestCase {
    public function testTrue() {
        $this->assertTrue(true);

        //  This line wont work without autloader.php
        $user = new User();
    }
}

The problem is that I need to load all my classes from autoloader.php:

<?xml version="1.0" encoding="UTF-8"?>
    <phpunit bootstrap="inc/autoload.php"></phpunit>

But I'n those classes I have a lot of $SERVER variables, like

$_SERVER['REMOTE_ADDR']
$_SERVER['HTTPS']
$_SERVER['SERVER_NAME']
$_SERVER['DOCUMENT_ROOT']
$_SERVER['REQUEST_URI']

This is the error I get:

Notice: Undefined index: REMOTE_ADDR in /Applications/MAMP/htdocs/sakkadentrainer/classes/App.php on line 674

How can I make those variables work? I would prefer to kind of "fake" them as env.variables from the phpunit.xml file, but I don't know if that's possible.

Thanks for you help!

My Setup: php 7.1.2, phpUnit 6.1.1, macOs Mojave, MAMP

SOLUTION: https://phpunit.de/manual/6.5/en/appendixes.configuration.html#appendixes.configuration.php-ini-constants-variables

like image 504
B. Rentrug Avatar asked Jul 17 '26 20:07

B. Rentrug


1 Answers

Referring to the Doc, you can Setting PHP INI settings, Constants and Global Variables, as example:

<php>
  <server name="REMOTE_ADDR" value="127.0.0.1"/>
</php>

Hope this help

like image 154
Matteo Avatar answered Jul 20 '26 10:07

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!