How to compare 2 URL adres with PHPUnit? - php

I am working on a task that is expose a xml file with given url. I want to test my code and I do this with PHPUnit. I used composer to install PHPUnit.
The example test that I want to run is this :
<?php
use PHPUnit\Framework\TestCase;
class IndexTest extends TestCase{
public function testGetXmlWithUrl(){
require 'index.php';
$XmlClass = new XmlReaderClass("localhost", "8000", "status.xml", "");
$url= $XmlClass->$url;
$myUrl = "http://localhost:8000/status.xml?password=";
$this->assertEquals($myUrl, $url);
}} ?>
TestCase class cannot be added. I mean even PhpUnit name is not colored in blue in the code. So I guess I could not include it in my project actually. Error is like:
Fatal error: Uncaught Error: Class 'PHPUnit\Framework\TestCase' not found in /Users/demetsen/Desktop/tests/IndexTest.php:4
My second problem is when I try to run testGetXmlWithUrl() method the result is :
Failed asserting that SimpleXMLElement Object (...) matches expected '\n ....
Why am I getting this result and how can I solve it?

A default phpunit.xml (or better, use phpunit.xml.dist, so you can copy/edit it locally if needed), can be created with phpunit --generate-configuration will include a line for bootstrap:
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.3/phpunit.xsd"
bootstrap="path/to/bootstrap.php"
<!-- more lines -->
</phpunit>
Here, the bootstrap="...." line can, at its simplest, point to the composer autoloader. PHPunit can also create a suitable file for you.
$ php ./phpunit-9.2.phar --generate-configuration # or vendor/bin/phpunit, via composer
PHPUnit 9.2.6 by Sebastian Bergmann and contributors.
Generating phpunit.xml in /home/username/code/test
Bootstrap script (relative to path shown above; default: vendor/autoload.php):
Tests directory (relative to path shown above; default: tests):
Source directory (relative to path shown above; default: src):
Generated phpunit.xml in /home/username/code/test
# optional, but useful:
# mv phpunit.xml phpunit.xml.dist # .dist will be read if .xml does not exist
The output file:
$ cat phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.2/phpunit.xsd"
bootstrap="vendor/autoload.php"
executionOrder="depends,defects"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
If you had something you needed to add to the bootstrap process, create a file with your needs, and you'd probably also add something like require __DIR__.'/vendor/autoload.php'; to setup the autoloading.

Related

PHPUnit Class not found error with Composer [duplicate]

I have just installed PHPUnit version 3.7.19 by Sebastian Bergmann via Composer and have written a class I would like to unit test.
I would like to have all my classes autoloaded into each unit test without having to use include or require at the top of my test but this is proving to be difficult!
This is what my directory structure looks like (a trailing / slash indicates a directory, not a file):
* composer.json
* composer.lock
* composer.phar
* lib/
* returning.php
* tests/
* returningTest.php
* vendor/
* bin/
* phpunit
* composer/
* phpunit/
* symfony/
* autoload.php
My composer.json file includes the following:
"require": {
"phpunit/phpunit": "3.7.*",
"phpunit/phpunit-selenium": ">=1.2"
}
My returning.php class file includes the following:
<?php
class Returning {
public $var;
function __construct(){
$this->var = 1;
}
}
?>
My returningTest.php test file includes the following:
<?php
class ReturningTest extends PHPUnit_Framework_TestCase
{
protected $obj = null;
protected function setUp()
{
$this->obj = new Returning;
}
public function testExample()
{
$this->assertEquals(1, $this->obj->var);
}
protected function tearDown()
{
}
}
?>
However, when I run ./vendor/bin/phpunit tests from the command-line, I get the following error:
PHP Fatal error: Class 'Returning' not found in
/files/code/php/db/tests/returningTest.php on line 8
I noticed that composer produced an autoload.php file in vendor/autoload.php but not sure if this is relevant for my problem.
Also, in some other answers on Stack Overflow people have mentioned something about using PSR-0 in composer and the namespace command in PHP, but I have not been successful in using either one.
Please help! I just want to autoload my classes in PHPUnit so I can just use them to create objects without worrying about include or require.
Update: 14th of August 2013
I have now created an Open Source project called PHPUnit Skeleton to help you get up and running with PHPUnit testing easily for your project.
Well, at first. You need to tell the autoloader where to find the php file for a class. That's done by following the PSR-0 standard.
The best way is to use namespaces. The autoloader searches for a Acme/Tests/ReturningTest.php file when you requested a Acme\Tests\ReturningTest class. There are some great namespace tutorials out there, just search and read. Please note that namespacing is not something that came into PHP for autoloading, it's something that can be used for autoloading.
Composer comes with a standard PSR-0 autoloader (the one in vendor/autoload.php). In your case you want to tell the autoloader to search for files in the lib directory. Then when you use ReturningTest it will look for /lib/ReturningTest.php.
Add this to your composer.json:
{
...
"autoload": {
"psr-0": { "": "lib/" }
}
}
More information in the documentation.
Now the autoloader can find your classes you need to let PHPunit know there is a file to execute before running the tests: a bootstrap file. You can use the --bootstrap option to specify where the bootstrap file is located:
$ ./vendor/bin/phpunit tests --bootstrap vendor/autoload.php
However, it's nicer to use a PHPunit configuration file:
<!-- /phpunit.xml.dist -->
<?xml version="1.0" encoding="utf-8" ?>
<phpunit bootstrap="./vendor/autoload.php">
<testsuites>
<testsuite name="The project's test suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
Now, you can run the command and it will automatically detect the configuration file:
$ ./vendor/bin/phpunit
If you put the configuration file into another directory, you need to put the path to that directory in the command with the -c option.
[Update2] Another simpler alternative approach is to use the autoload-dev directive in composer.json (reference). The benefit is that you don't need to maintain two bootstrap.php (one for prod, one for dev) just in order to autoload different classes.
{
"autoload": {
"psr-4": { "MyLibrary\\": "src/" }
},
"autoload-dev": {
"psr-4": { "MyLibrary\\Tests\\": "tests/" }
}
}
[Update] Wouter J's answer is more complete. But mine can help people who want to set up PSR-0 autoloading in tests/ folder.
Phpunit scans all files with this pattern *Test.php. So we don't need to autoload them ourselves. But we still want to autoload other supporting classes under tests/ such as fixture/stub or some parent classes.
An easy way is to look at how Composer project itself is setting up the phpunit test. It's actually very simple. Note the line with "bootstrap".
reference: https://github.com/composer/composer/blob/master/phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="Composer Test Suite">
<directory>./tests/Composer/</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>slow</group>
</exclude>
</groups>
<filter>
<whitelist>
<directory>./src/Composer/</directory>
<exclude>
<file>./src/Composer/Autoload/ClassLoader.php</file>
</exclude>
</whitelist>
</filter>
</phpunit>
reference: https://github.com/composer/composer/blob/master/tests/bootstrap.php
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman#naderman.de>
* Jordi Boggiano <j.boggiano#seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
error_reporting(E_ALL);
$loader = require __DIR__.'/../src/bootstrap.php';
$loader->add('Composer\Test', __DIR__);
The last line above is autoloading phpunit test classes under the namespace Composer\Test.
None of these answers were what I was looking for. Yes PHPUnit loads test files, but not stubs/fixtures. Chaun Ma's answer doesn't cut it because running vendor/bin/phpunit already includes the autoload, so there's no way to get an instance of the autoloader to push more paths to it's stack at that point.
I eventually found this in the docs:
If you need to search for a same prefix in multiple directories, you
can specify them as an array as such:
{
"autoload": {
"psr-0": { "Monolog\\": ["src/", "lib/"] }
}
}
There is a really simple way to set up phpunit with autoloading and bootstap. Use phpunit's --generate-configuration option to create your phpunit.xml configuration in a few seconds-:
vendor/bin/phpunit --generate-configuration
(Or just phpunit --generate-configuration if phpunit is set in your PATH). This option has been available from version phpunit5 and upwards.
This option will prompt you for your bootstrap file (vendor/autoload.php), tests and source directories. If your project is setup with composer defaults (see below directory structure) the default options will be all you need. Just hit RETURN three times!
project-dir
-- src
-- tests
-- vendor
You get a default phpunit.xml which is good to go. You can of course edit to include any specialisms (e.g. colors="true") you require-:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.1/phpunit.xsd"
bootstrap="vendor/autoload.php"
executionOrder="depends,defects"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
If you are using PHPUnit 7 you can make your classes from src/ folder to autoload in tests like this:
Ensure that your composer.json file looks similar to this:
{
"autoload": {
"classmap": [
"src/"
]
},
"require-dev": {
"phpunit/phpunit": "^7"
}
}
To apply changes in composer.json run command:
composer install
Finally you can run tests in tests/ folder:
./vendor/bin/phpunit tests/

Unable to run PHPUnit Test with relative include path

I am doing an assignment and I was asked not to modify the Test File (CheckPayTest.php). I try to run test but phpunit cannot find the file and the file is correctly placed in the directory. Is it possible to make phpunit see this file when running the test
CheckPayTest.php
<?php declare(strict_types=1);
namespace cms\tests;
use PHPUnit\Framework\TestCase;
class CheckPayTest extends TestCase
{
public function test_File_Read()
{
$readFile = include './../Creative.php';
self::assertTrue($readFile);
}
}
File to include Creative.php
<?php declare(strict_types=1);
namespace cms;
return true;
phpunit.xml Config
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="My Test Suite">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
</phpunit>
Error
1) cms\tests\CheckPayTest::test_File_Read
include(./../Creative.php): failed to open stream: No such file or directory
Could this problem be solved without modifying CheckPayTest.php
Yes, you can make it run without modifying CheckPayTest.php.
Unfortunately someone who wrote this test was not aware of how php executable resolves relative directory paths - so the problem jumped out.
The solution is to change the directory from where php script starts to execute - php resolves relative paths from within any file during execution in reference to entry point of script start. The solution is to cd (change directory) to where this path './../Creative.php' becomes valid and run phpunit script from there.
Anyway, this solution is really poor - the correct way to fix it is to change first dot from the path to php magic constant __DIR__ which always provide absolute path to directory in which code was executed. I think you should change this file anyway - otherwise it will remain poorly written.
Try to change './../Creative.php' into __DIR__ . '/../Creative.php'

phpunit no tests executed

I have a 'No tests executed' with phpunit..
This line works
$ phpunit install/InstallDbTest.php
...
<result expected>
...
$ cat suites/installtests.xml
<phpunit>
<testsuites>
<testsuite name="database">
<file>install/InstallDbTest.php</file>
</testsuite>
</testsuites>
</phpunit>
$ phpunit -c suites/installtests.xml
PHPUnit 4.7.4 by Sebastian Bergmann and contributors.
Time: 130 ms, Memory: 11.25Mb
No tests executed!
Does anyone can tell me what I am doing wrong ?
Thanks in advance!
You need to correct the path in your phpunit.xml.
It is trying to find the filesuites/install/InstallDbTest.php. Since the file doesn't exist, no tests are run and you get the message.
Change the configuration to the following:
<phpunit>
<testsuites>
<testsuite name="database">
<file>../install/InstallDbTest.php</file>
</testsuite>
</testsuites>
</phpunit>
File paths in phpunit.xml are all relative to the location of the xml file.
Maybe in the InstallDbTest.php file you are missing:
<?php
...
For those of you who you use a different bootstrap file than the Composer's autoload file, make sure you don't use one of your test case classes.
Indeed, PHPUnit (version 6.2 in my case) add to the running TestSuite all PHP files for which no class is loaded yet (see how it's done in the code). From the TestSuite::addTestFile($filename) method:
$classes = get_declared_classes();
$filename = Fileloader::checkAndLoad($filename);
$newClasses = \array_diff(\get_declared_classes(), $classes);
So if your class already belong to the get_declared_classes it will be ignored.
To summarize: don't use your test class before ;)

Entity Class not found PHPUnit Test

Below are the paths where files are located,
src\TW\Talk\Entity\Talk.php
src\Tests\Talk\Entity\TalkTest.php
src\phpunit.xml.dist
In TalkTest.php, I have included PHPUnit and the entity Talk.
require_once 'TW/Talk/Entity/Talk.php';
require('PHPUnit/Autoload.php');
Class TalkTest extends PHPUnit_Framework_TestCase
{
...
}
In phpunit.xml.dist file, I have,
<phpunit>
<testsuites>
<testsuite name="TW">
<file>Tests/Talk/Entity/TalkTest.php</file>
</testsuite>
</testsuites>
</phpunit>
I am running phpunit command from src directory, I am getting error that Fatel Error: Class 'Tests\TW\Talk\Enity\Talk' not found.
For reference, I am referring to php-object-freezer-master which has similar structure.
Any idea why the TalkTest is not able to find Talk class ?
phpunit command is trying to find Talk entity in Tests folder.
Changing phpunit.xml.dist to
<phpunit bootstrap="loader.php">
<testsuites>
<testsuite name="TW_Talk">
<directory>Tests</directory>
</testsuite>
</testsuites>
</phpunit>
and loader file as,
<?php
function tw_test_autoloader($class) {
if(file_exists(__DIR__."\\" . $class . ".php"))
require_once(__DIR__."\\" . $class . ".php");
}
spl_autoload_register('tw_test_autoloader');
Worked for me.
But still if I replace directory tag to file
<file>Tests\TW\Talk\Entity\TalkTest.php</file>
It does not work.
Check your include_path:
echo get_include_path();
It should contain the directory to which your TW/Talk/Entity/Talk.php is relative. If it is not there, then you must add it either to php.ini or to PHPUnit's bootstrap.
You can easily test if PHP can find your file using your include path with this:
var_dump( stream_resolve_include_path('TW/Talk/Entity/Talk.php') );

Autoloading classes in PHPUnit using Composer and autoload.php

I have just installed PHPUnit version 3.7.19 by Sebastian Bergmann via Composer and have written a class I would like to unit test.
I would like to have all my classes autoloaded into each unit test without having to use include or require at the top of my test but this is proving to be difficult!
This is what my directory structure looks like (a trailing / slash indicates a directory, not a file):
* composer.json
* composer.lock
* composer.phar
* lib/
* returning.php
* tests/
* returningTest.php
* vendor/
* bin/
* phpunit
* composer/
* phpunit/
* symfony/
* autoload.php
My composer.json file includes the following:
"require": {
"phpunit/phpunit": "3.7.*",
"phpunit/phpunit-selenium": ">=1.2"
}
My returning.php class file includes the following:
<?php
class Returning {
public $var;
function __construct(){
$this->var = 1;
}
}
?>
My returningTest.php test file includes the following:
<?php
class ReturningTest extends PHPUnit_Framework_TestCase
{
protected $obj = null;
protected function setUp()
{
$this->obj = new Returning;
}
public function testExample()
{
$this->assertEquals(1, $this->obj->var);
}
protected function tearDown()
{
}
}
?>
However, when I run ./vendor/bin/phpunit tests from the command-line, I get the following error:
PHP Fatal error: Class 'Returning' not found in
/files/code/php/db/tests/returningTest.php on line 8
I noticed that composer produced an autoload.php file in vendor/autoload.php but not sure if this is relevant for my problem.
Also, in some other answers on Stack Overflow people have mentioned something about using PSR-0 in composer and the namespace command in PHP, but I have not been successful in using either one.
Please help! I just want to autoload my classes in PHPUnit so I can just use them to create objects without worrying about include or require.
Update: 14th of August 2013
I have now created an Open Source project called PHPUnit Skeleton to help you get up and running with PHPUnit testing easily for your project.
Well, at first. You need to tell the autoloader where to find the php file for a class. That's done by following the PSR-0 standard.
The best way is to use namespaces. The autoloader searches for a Acme/Tests/ReturningTest.php file when you requested a Acme\Tests\ReturningTest class. There are some great namespace tutorials out there, just search and read. Please note that namespacing is not something that came into PHP for autoloading, it's something that can be used for autoloading.
Composer comes with a standard PSR-0 autoloader (the one in vendor/autoload.php). In your case you want to tell the autoloader to search for files in the lib directory. Then when you use ReturningTest it will look for /lib/ReturningTest.php.
Add this to your composer.json:
{
...
"autoload": {
"psr-0": { "": "lib/" }
}
}
More information in the documentation.
Now the autoloader can find your classes you need to let PHPunit know there is a file to execute before running the tests: a bootstrap file. You can use the --bootstrap option to specify where the bootstrap file is located:
$ ./vendor/bin/phpunit tests --bootstrap vendor/autoload.php
However, it's nicer to use a PHPunit configuration file:
<!-- /phpunit.xml.dist -->
<?xml version="1.0" encoding="utf-8" ?>
<phpunit bootstrap="./vendor/autoload.php">
<testsuites>
<testsuite name="The project's test suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
Now, you can run the command and it will automatically detect the configuration file:
$ ./vendor/bin/phpunit
If you put the configuration file into another directory, you need to put the path to that directory in the command with the -c option.
[Update2] Another simpler alternative approach is to use the autoload-dev directive in composer.json (reference). The benefit is that you don't need to maintain two bootstrap.php (one for prod, one for dev) just in order to autoload different classes.
{
"autoload": {
"psr-4": { "MyLibrary\\": "src/" }
},
"autoload-dev": {
"psr-4": { "MyLibrary\\Tests\\": "tests/" }
}
}
[Update] Wouter J's answer is more complete. But mine can help people who want to set up PSR-0 autoloading in tests/ folder.
Phpunit scans all files with this pattern *Test.php. So we don't need to autoload them ourselves. But we still want to autoload other supporting classes under tests/ such as fixture/stub or some parent classes.
An easy way is to look at how Composer project itself is setting up the phpunit test. It's actually very simple. Note the line with "bootstrap".
reference: https://github.com/composer/composer/blob/master/phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="Composer Test Suite">
<directory>./tests/Composer/</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>slow</group>
</exclude>
</groups>
<filter>
<whitelist>
<directory>./src/Composer/</directory>
<exclude>
<file>./src/Composer/Autoload/ClassLoader.php</file>
</exclude>
</whitelist>
</filter>
</phpunit>
reference: https://github.com/composer/composer/blob/master/tests/bootstrap.php
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman#naderman.de>
* Jordi Boggiano <j.boggiano#seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
error_reporting(E_ALL);
$loader = require __DIR__.'/../src/bootstrap.php';
$loader->add('Composer\Test', __DIR__);
The last line above is autoloading phpunit test classes under the namespace Composer\Test.
None of these answers were what I was looking for. Yes PHPUnit loads test files, but not stubs/fixtures. Chaun Ma's answer doesn't cut it because running vendor/bin/phpunit already includes the autoload, so there's no way to get an instance of the autoloader to push more paths to it's stack at that point.
I eventually found this in the docs:
If you need to search for a same prefix in multiple directories, you
can specify them as an array as such:
{
"autoload": {
"psr-0": { "Monolog\\": ["src/", "lib/"] }
}
}
There is a really simple way to set up phpunit with autoloading and bootstap. Use phpunit's --generate-configuration option to create your phpunit.xml configuration in a few seconds-:
vendor/bin/phpunit --generate-configuration
(Or just phpunit --generate-configuration if phpunit is set in your PATH). This option has been available from version phpunit5 and upwards.
This option will prompt you for your bootstrap file (vendor/autoload.php), tests and source directories. If your project is setup with composer defaults (see below directory structure) the default options will be all you need. Just hit RETURN three times!
project-dir
-- src
-- tests
-- vendor
You get a default phpunit.xml which is good to go. You can of course edit to include any specialisms (e.g. colors="true") you require-:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.1/phpunit.xsd"
bootstrap="vendor/autoload.php"
executionOrder="depends,defects"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
If you are using PHPUnit 7 you can make your classes from src/ folder to autoload in tests like this:
Ensure that your composer.json file looks similar to this:
{
"autoload": {
"classmap": [
"src/"
]
},
"require-dev": {
"phpunit/phpunit": "^7"
}
}
To apply changes in composer.json run command:
composer install
Finally you can run tests in tests/ folder:
./vendor/bin/phpunit tests/

Categories