Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Determine if PHPUnit Tests are Running?

Tags:

phpunit

I currently have a problem that I have to work around in legacy code to get our interaction with a PHP Extension to work properly (Singleton Testing Question).

As such, I do not want to execute this code when running our normal production code with the application. Therefore, I need to check in regular PHP code if the code being executed is being executed as part of a test or not.

Any suggestions on how to determine this? I thought about a defined variable tied to the presence of the test files themselves (we do not ship the tests to customers) but our developers need the Extension to work normally, while the CI server needs to run the tests.

Would a Global set in the PHPUnit.xml file be recommended? Other thoughts?

like image 414
Steven Scott Avatar asked Apr 20 '12 20:04

Steven Scott


People also ask

What is a PHPUnit test?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

How do I start PHPUnit?

PHPUnit InstallationThe first command creates a folder in your current directory, test-project and the second command moves into it. The last command starts an interactive shell. Follow the prompt, filling in the details as required (the default values are fine).

What is assertion in PHPUnit?

The assertion methods are declared static and can be invoked from any context using PHPUnit\Framework\Assert::assertTrue() , for instance, or using $this->assertTrue() or self::assertTrue() , for instance, in a class that extends PHPUnit\Framework\TestCase .


2 Answers

An alternative approach is to set a constant in the PHP section of your phpunit.xml.*:

<php>    <const name="PHPUNIT_YOURAPPLICATION_TESTSUITE" value="true"/> </php> 

In your PHP application, you might then use the following check:

if (defined('PHPUNIT_YOURAPPLICATION_TESTSUITE') && PHPUNIT_YOURAPPLICATION_TESTSUITE) {      echo 'TestSuite running!'; } 
like image 80
Jens A. Koch Avatar answered Sep 25 '22 06:09

Jens A. Koch


Define a constant in your PHPUnit bootstrap.php file. This is executed before loading or running any tests. This shouldn't impact developers running the application normally--just the unit tests.

like image 26
David Harkness Avatar answered Sep 24 '22 06:09

David Harkness