3Answers
  • 5
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Pass variable to PhpUnit

I developed a set of test cases using phpunit used for testing both development site and the production site. The only difference is the domain name. How can I pass the domain from command line to phpunit test cases so that I do not need to modify every file?

In your phpunit-bootstrap.php you can do something like this:

$site = getenv('DOMAIN');

and use

<php>
  <env name="DOMAIN" value="http://production.com"/>
</php>

in your phpunit.xml file as shown in the documentation.

The downside of this approach is that you need to have two different xml files.


Other options are using a custom wrapper script around phpunit like @DavidHarkness showed which tends to work out well

or, if you don't want to run those tests in an automated way (or use both approaches) to do something like:

$site = getenv('DOMAIN');
if(!$site) {
    echo "Enter Domain: ";
    $site = fgets(STDIN);
}

and have the runner check the environment and if nothing is there ask you for the domain.


Env or define or anything else

The same goes for pretty much every way that php can take in input from the outside world.

<php>
  <define name="DOMAIN" value="http://production.com"/>
</php>

also works in case you are using a constant anyways, for example.

  • 12
Reply Report

You could set an environment variable before running the tests. To make this easier on yourself, create a simple script to export the variable and run the tests.

#!/bin/bash

USAGE="Usage: $0 <domain> [file-or-directory]"

if [ "$#" == "0" ]; then
    echo "$USAGE"
    exit 1
fi

export TEST_DOMAIN=$1
shift
phpunit $*

In your base test case you can access this value using getenv:

$domain = getenv('TEST_DOMAIN');
  • 4
Reply Report

I ran into this too. One way you can do this with bash is to export the ENV variables you want to pass in and chain the phpunit call using ; like so:

#: HOST_NAME="my.host.com"; phpunit MyTestFile.php

That will create a HOST_NAME environment variable and then immediately call your unit test.

Then within your test script you can access the HOST_NAME variable using something like:

$host = getenv('HOST_NAME');
  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions