I have little problem when I'm trying to run PHPUnit test in IDE PhpStorm.
I use composer file which looks:
{
"require": {
"phpunit/phpunit": "3.7.19"
}
}
Now when I run test I recive exception:
PHP Fatal error: Uncaught exception 'PHPUnit_Framework_Exception' with message 'Class "PHPUnit_Extensions_RepeatedTest" does not extend PHPUnit_Framework_TestCase.'
What is wrong? When I included pear installed version test working OK.
//EDIT
Sample test class:
class ReaderTest extends PHPUnit_Framework_TestCase
{
/**
* #test
*/
public function shouldGetReadedValue ()
{
$this->assertTrue(true);
}
}
//EDIT2
Trace:
/usr/bin/php /tmp/ide-phpunit.php --no-configuration /path/to/my/project
Testing started at 14:53 ...
PHP Fatal error: Uncaught exception 'PHPUnit_Framework_Exception' with message 'Class "PHPUnit_Extensions_RepeatedTest" does not extend PHPUnit_Framework_TestCase.' in /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php:183
Stack trace:
#0 /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php(315): PHPUnit_Framework_TestSuite->__construct(Object(ReflectionClass))
#1 /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php(389): PHPUnit_Framework_TestSuite->addTestSuite(Object(ReflectionClass))
#2 /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php(416): PHPUnit_Framework_TestSuite->addTestFile('/var/www/php-sh...')
#3 /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/Runner/BaseTestRunner.php(96): PHPUnit_Framework_TestSuite->addTestFiles(Array)
#4 /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/TextUI/Command.php(150): PHPUnit_Runner_BaseTestRunner->getTest('/var/www/php-sh...', '', A in /path/to/my/project/vendor/phpunit/phpunit/PHPUnit/Framework/TestSuite.php on line 183
Process finished with exit code 255
I found solution about this problem.
In Edit configurations in directory I set path to my tests catalog (/path/to/my/project/tests), after this tests are running properly.
This is what worked for me, thanks to Piotr's answer above, but I'm providing with a bit more exact detail here all the steps I had to do:
Steps to make it work (test in PHPStorm 8.0.1):
1) In Preferences > PHP > PHPUnit make sure that nothing is set for Default configuration file or default bootstrap file.
2) Make a custom PHPUnit Configuration via Run > Edit Configurations > in the Command Line subsection, and be sure to:
a) set Custom working directory: to be /absolute/path/to/vendor.
b) check "Use alternative configuration file:" and set it to /absolute/path/to/vendor/your_app/(sub_app_if_applicable)/phpunit.xml.dist
Then you can run any test class in the suite by specifying the class and file, or just check "Defined in the configuration file" to run all of them according to the config.
I have same problem when using composer.
The solution is to put your test file in its own directory. Here is my working phpunit, i put all my test in test directory.
<phpunit bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="true">
<testsuites>
<testsuite name="Test Suite">
<directory>test</directory>
</testsuite>
</testsuites>
</phpunit>
Hope it solves if anyone have same problem.. :)
Inside the PHPUnit_Framework_TestSuite, this code exists in the constructor:
if (!$theClass->isSubclassOf('PHPUnit_Framework_TestCase')) {
throw new PHPUnit_Framework_Exception(
'Class "' . $theClass->name . '" does not extend PHPUnit_Framework_TestCase.'
);
}
I see in your example that you are extending PHPUnit_Framework_TestCase but the error suggests you are using PHPUnit_Extensions_RepeatedTest which extends PHPUnit_Extensions_TestDecorator which ultimately extends PHPUnit_Framework_Assert
PHPUnit_Framework_Assert
|
--PHPUnit_Extensions_TestDecorator
|
--PHPUnit_Extensions_RepeatedTest
Double check your tests because the error suggests you are attempting to run a TestSuite using a test extending PHPUnit_Extensions_RepeatedTest. Were you instead trying to extend PHUnit using Test Decorators?
http://docs.tadiavo.com/phpunit/www.phpunit.de/pocket_guide/3.1/en/extending-phpunit.html
That is all the advice I can currently offer without seeing your actual tests and how you are running them.
Related
I have a lot of problems trying to intall phpunit, maybe my knowledge isn't enought or the guide is very incomplete.
First, the install, I tried all the ways, globally, with "downloaded PHAR file directly" or with "sudo apt-get install phpunit" but when I tried to do:
$phpunit -v
bash: /usr/bin/phpunit: No chuch file or directory
if I do:
$ ll /usr/local/bin (I know, the path is different, other unexplicable event)
-rwxr-xr-x 1 user user 2784899 abr 29 17:09 phpunit*
but
$ sudo phpunit --version
PHPUnit 7.1.5 by Sebastian Bergmann adn contributors.
ok, looks better, so I tried to make the first example
<?php
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
public function testPushAndPop()
{
$stack = [];
$this->assertSame(0, count($stack));
array_push($stack, 'foo');
$this->assertSame('foo', $stack[count($stack)-1]);
$this->assertSame(1, count($stack));
$this->assertSame('foo', array_pop($stack));
$this->assertSame(0, count($stack));
}
}
but it give me the next error:
PHP Fatal error: Class 'PHPUnit\Framework\Testcase' not found in /var/www/html/phpunit/index.php on line 4
I'm using Ubuntu 18 and php 7.2
Any idea?
When you are running PHPUnit from the command line, you also need to include a 'bootstrap' file - it can be as simple as the composer autoload.php file:
phpunit --bootstrap vendor/autoload.php
Longer term, that configuration would be put into the phpunit.xml file so it is read, and run automatically by PHPunit.
<!-- file: phpunit.xml
src/autoload.php would also include the ./vendor/autoload.php file
and do any other locally required setup -->
<phpunit bootstrap="src/autoload.php">
<testsuites>
<testsuite name="money">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
Ok, I start to understand some things.
First #Sebastian Bergmann give me the clue, with this example, it works.
But if you start with the documentation you never found it. I think it's an error and can confuse a begginer like me.
Yet I can't install phpunit with PHAR or globally, maybe it could be a future new post.
Thanks for all
I'm new in PHPUnit and unit-testing, so I was install PHPUnit and phar via composer and everything had been going fine until I was try to start my simple test. I'm using PhpStorm where I can see all classes were autoload, but when I trying to start my test I got an error:
Fatal error: Class 'PharIo\Manifest\Simple' not found in C:\xampp\htdocs\mydocs\
I don't understand why he is looking for It in folder upper than PHPUnit is exists ?
I was trying to configure autoload section in composer.json and checking settings in phpunit.xml but nothing works.
Add:
I have to reinstall PHPUnit without PharIO, so now I have a little bit of progress, now I have a situation where I can test my class if I make require_once line with a name of the tested class. It looks like:
require_once '../src/Simple.php';
class SimpleTest extends PHPUnit_Framework_TestCase
{
public function testAdd() {
$sum = new Simple();
$this->assertEquals(5, $sum->add(2, 3));
}
}
So my simple class is:
class Simple {
public function add($a, $b) {
return (int) $a + (int) $b;
}
}
But, of course, I want to use namespaces. I try to make some changes based on this question: Autoloading classes in PHPUnit using Composer and autoload.php (I was try even use that repo for test, but an error is still exists) but nothing works for me. I was try to edit my autoload section in the composer.json like this
"autoload": {
"psr-4": {
"app\\": "src/"
}
},
But an error is still exists, another words autoload cannot see It. I was create phpunit.xml and phpunit.dist.xml with a same settings
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/3.7/phpunit.xsd"
backupGlobals="true"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="./tests/bootstrap.php">
<testsuites>
<testsuite name="The project's test suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
and I made tests/bootstrap.php too with
require_once '../vendor/autoload.php';
I know this is an old question, but maybe you need to do
composer dump-autoload for composer to generate the map of classes.
I wasted 30mins trying to understand why PHPUnit was giving me:
Cannot stub or mock class or interface XXX because it doesn't exists
You should specify the script with autoloading classes.
You can either specify the file with autoloading in XML-file, as suggested in the other answer, or just by specifying --bootstrap option in your command to run tests:
phpunit --bootstrap vendor/autoload.php tests
Composer's autoload relies on configuration located in the vendor/autoload.php file which needs to be loaded at some point in your execution thread. You application already includes this and that's why it works, but the tests use a different entry point so you need to configure it with a file called phpunit.xml.dist.
Assuming your file structure is something like:
app/
src/
tests/
bootstrap.php <- create it in your test folder
vendor/
...
composer.json
composer.lock
phpunit.xml.dist <- create it if does not exist
You can see the various options here, but for a basic config, you can use this.
File phpunit.xml.dist:
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/3.7/phpunit.xsd"
backupGlobals="true"
backupStaticAttributes="false"
bootstrap="tests/bootstrap.php">
</phpunit>
File tests/bootstrap.php:
require_once '../vendor/autoload.php';
You should run phpunit from the root.
I have a fairly simple problem that I cannot seem to figure out.
I am developing an OOP-based PHP application using the Composer Dependency Manager, PHPUnit for testing. I am hosting the repository on GitLab and am using GitLab-CI to run the PHPUnit tests.
My file directory is fairly simple:
├──_data
├──_2016
├──_federal
├──fit.json
├──_libs
├──_paycheckCalculator
├──paycheck.php
├──taxCalc.php
├──_public_html
├──index.php
├──_vendor
├──[composer dependencies]
├──autoload.php
├──_tests
├──paycheckTest.php
├──taxCalcTest.php
├──_templates
├──[Twig templates]
taxCalc.php contains:
public static function calcFIT($taxableWages, array $taxStatus, int $frequency = 52):float {
$fitFile = "../data/2016/federal/fit.json";
...
That works just fine on my production server and I can run the PHPunit tests just fine via PHPUnit integration with PhpStorm, but when I try to get GitLab-CI to work I consistently get an error:
...
$ vendor/bin/phpunit --configuration phpunit.xml PHPUnit 5.5.4 by
Sebastian Bergmann and contributors.
EE..EII 7
/ 7 (100%)
Time: 32 ms, Memory: 4.00MB
There were 3 errors:
1) paycheckTest::calcNetTest
file_get_contents(../data/2016/federal/fit.json): failed to open
stream: No such file or directory
/builds/calebrw/paycheckCalculator/libs/paycheckCalculator/taxCalc.php:100
/builds/calebrw/paycheckCalculator/libs/paycheckCalculator/paycheck.php:49
/builds/calebrw/paycheckCalculator/libs/paycheckCalculator/paycheck.php:28
/builds/calebrw/paycheckCalculator/tests/paycheckTest.php:34
2) paycheckTest::calcTaxesTest
file_get_contents(../data/2016/federal/fit.json): failed to open
stream: No such file or directory
/builds/calebrw/paycheckCalculator/libs/paycheckCalculator/taxCalc.php:100
/builds/calebrw/paycheckCalculator/tests/paycheckTest.php:58
3) taxCalcTest::calcFITTest
file_get_contents(../data/2016/federal/fit.json): failed to open
stream: No such file or directory
/builds/calebrw/paycheckCalculator/libs/paycheckCalculator/taxCalc.php:100
/builds/calebrw/paycheckCalculator/tests/taxCalcTest.php:53
ERRORS! Tests: 7, Assertions: 11, Errors: 3, Incomplete: 2. ERROR:
Build failed: exit code 1
My .gitlab_ci.yml is as follows:
# Select image from https://hub.docker.com/_/php/
image: php:7.0
# Select what we should cache
cache:
paths:
- vendor/
before_script:
# Install git, the php image doesn't have installed
- apt-get update -yqq
- apt-get install git -yqq
# Install composer
- curl -sS https://getcomposer.org/installer | php
# Install all project dependencies
- php composer.phar install
PHPUnit:testsuite:
script:
- vendor/bin/phpunit --configuration phpunit.xml
My phpunit.xml file contains:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Paycheck Tests">
<directory>tests/</directory>
</testsuite>
</testsuites>
<php>
<includePath>/builds/calebrw/paycheckCalculator</includePath>
</php>
</phpunit>
Please note that I've used this with or without the <includePath> tag and there is no difference if I use <includePath>/../</includePath> or anything else for that matter.
I appreciate any help you can give.
EDIT:
I finally got this to work. I added a function (in the global space for now) to my config.php file:
/**
* Required Functions
*/
function getDirectory(bool $html = false):string
{
$htmlBaseDirectory = '/webprojects/paycheckCalculator';
if ($html == true) {
return $htmlBaseDirectory;
} else {
return dirname(__DIR__);
}
}
That meant I could update my index.php:
require_once('config.php'); // Configuration Variables
require_once( getDirectory() . '/vendor/autoload.php'); // Composer Autoload
$dir = getDirectory(true) . $htmlPublicDirectory; // Combined variable needed for Twig compatibility
but I was still having problems with the GitLab-Ci runner having yet a completely different environment that doesn't call my config.php at all, so I added a fix (or hack really) to get the test to pass to taxCalc.php:
if (getenv('CI_BUILD_ID') !== false) {
define('MAIN_PATH', '/builds/calebrw/paycheckCalculator/');
} else {
define('MAIN_PATH', dirname(__DIR__));
}
...
class taxCalc
{
...
public static function calcFIT($taxableWages, array $taxStatus, int $frequency = 52):float {
$fitFile = MAIN_PATH . "/data/2016/federal/fit.json";
And now the build passes.
Thanks for all the help to both people who responded.
Make sure that the file is commited (usually you don't commit data you may place it under resources). I think you did already.
The second thing is also just a suggestion:
define a PATH constant and use this. Because in your case you never know where is your current working directory.
Define a bootstrap file in phpunit and define the MAIN_PATH. Example:
<?php
define('MAIN_PATH', dirname(__DIR__));
require MAIN_PATH . '/vendor/autoload.php';
In the index you have to provide this MAIN_PATH too and in calcFit you write:
<?php
function calcFit() {
$fitFile = MAIN_PATH . '/data/2016/federal/fit.json';
}
The issue is very probably that you are using a relative path in your require. See here for explanations and solutions : PHP - Failed to open stream : No such file or directory
I have already posted this question on php unit first test symfony
I installed phpunit via the composer as a per project installation.
When trying vendor/bin>phpunit -c ../../app every thing is ok and I get a positive answer.
Whereas this command give the answer to all the tests in the tests directory.
But I want the result to every test alone.
When trying /vendor/bin>phpunit -c ../../src/xxx/Bundle/tests/entity/yyy.php and I get the following message : could not load c:\wamp\www\symfony\src/xxx/Bundle/tests/entity/yyy.php Parse PI : PI php never end ... Start ttag expected, '<' not found
and when trying /vendor/bin>phpunit -c ../../src/xxx/Bundle/tests/entity/yyy and I get the following message : could not read "..\..\src/xxx/Bundle/tests/entity/yyy"
Could anybody help me to know how should I write the command and from where execute it???
Any ideas???
Don't use the -c option here. The -c option is a shortcut for --configuration and it points to the directory of a PHPunit configuration file (like app/phpunit.xml.dist). That configuration tells PHPunit where to look for the test classes and some other configuration, like the bootstrap file.
If you want to run tests for a specific test, you can do it like phpunit path/to/tests/MyTest.php. But you'll loose the autoloading then. To get that back, you can use the --bootstrap option to point to the bootstrap file. So it'll be phpunit --bootstrap vendor/autoload.php path/to/tests/MyTest.php.
If you want to run this command more often, you can better edit the app/phpunit.xml.dist file and create a new suite:
<?xml version="1.0" encoding="utf-8" ?>
<phpunit ...>
<!-- ... -->
<testsuites>
<testsuite name="MyBundle">
<file>path/to/tests/MyTest.php</file>
</testsuite>
</testsuites>
<!-- ... -->
</phpunit>
And then run: phpunit -c app --testsuite MyBundle
Happened with me too, but in fact we are misreading the documentation you are forgetting 'app' in the command line look:
phpunit -c app src/AppBundle/Tests/Util/CalculatorTest.php
Note the app parameter in command sentence.
Why I'm getting this PHP error?
Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...
For those arriving here after updating phpunit to version 6 or greater released on 2017-02-03 (e.g. with composer), you may be getting this error because phpunit code is now namespaced (check changelog).
You will need to refactor things like \PHPUnit_Framework_TestCase to \PHPUnit\Framework\TestCase
The PHPUnit documentation says used to say to include/require PHPUnit/Framework.php, as follows:
require_once ('PHPUnit/Framework/TestCase.php');
UPDATE
As of PHPUnit 3.5, there is a built-in autoloader class that will handle this for you:
require_once 'PHPUnit/Autoload.php';
Thanks to Phoenix for pointing this out!
For higher version of phpunit such as 6.4
You must use the namespace PHPUnit\Framework\TestCase
use TestCase instead PHPUnit_Framework_TestCase
// use the following namespace
use PHPUnit\Framework\TestCase;
// extend using TestCase instead PHPUnit_Framework_TestCase
class SampleTest extends TestCase {
}
I was running PHPUnit tests on PHP5, and then, I needed to support PHP7 as well. This is what I did:
In composer.json:
"phpunit/phpunit": "~4.8|~5.7"
In my PHPUnit bootstrap file (in my case, /tests/bootstrap.php):
// PHPUnit 6 introduced a breaking change that
// removed PHPUnit_Framework_TestCase as a base class,
// and replaced it with \PHPUnit\Framework\TestCase
if (!class_exists('\PHPUnit_Framework_TestCase') && class_exists('\PHPUnit\Framework\TestCase'))
class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');
In other words, this will work for tests written originally for PHPUnit 4 or 5, but then needed to work on PHPUnit 6 as well.
You may get this error because you namespaced the file. If so you will need to specify that PHPUnit_Framework_TestCase is in the global namespace by preceding it with a backslash:
namespace AcmeInc\MyApplication\Tests
class StackTest extends \PHPUnit_Framework_TestCase {}
I submitted a crude PR to start conversation for correcting the documentation.
You can simply install PHPUnit to run commands (https://github.com/sebastianbergmann/phpunit/#php-archive-phar):
wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
mv phpunit.phar /usr/local/bin/phpunit
Run single test
And then run PHPunit test:
phpunit test.php
Content of test file is following:
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
}
public function testSave()
{
}
}
Run test suite
Configuration of test suite: demosuite.xml. demo is directory containing all tests. Test files must be named as *_test.php (suffix).
<testsuites>
<testsuite name="DemoTestSuite">
<directory suffix="test.php">demo</directory>
</testsuite>
</testsuites>
Test suite runs with following commands:
phpunit -c demosuite.xml --testsuite DemoTestSuite
Assumption:
Phpunit (3.7) is available in the console environment.
Action:
Enter the following command in the console:
SHELL> phpunit "{{PATH TO THE FILE}}"
Comments:
You do not need to include anything in the new versions of PHPUnit unless you do not want to run in the console. For example, running tests in the browser.
I use ZF2 and work for me when replaced 'PHPUnit_Framework_TestCase' to '\PHPUnit\Framework\TestCase'
I got it working with
include("vendor/autoload.php");
at the top of my test function.
If you have Centos or other Linux distribution you have to install phpunit package, I did that with yum install phpunit and it worked. Maybe you can have to add a repository, but I think it has to work smooth with the default ones (I have CentOS 7)
It may well be that you're running WordPress core tests, and have recently upgraded your PhpUnit to version 6. If that's the case, then the recent change to namespacing in PhpUnit will have broken your code.
Fortunately, there's a patch to the core tests at https://core.trac.wordpress.org/changeset/40547 which will work around the problem. It also includes changes to travis.yml, which you may not have in your setup; if that's the case then you'll need to edit the .diff file to ignore the Travis patch.
Download the "Unified Diff" patch from the bottom of https://core.trac.wordpress.org/changeset/40547
Edit the patch file to remove the Travis part of the patch if you don't need that. Delete from the top of the file to just above this line:
Index: /branches/4.7/tests/phpunit/includes/bootstrap.php
Save the diff in the directory above your /includes/ directory - in my case this was the Wordpress directory itself
Use the Unix patch tool to patch the files. You'll also need to strip the first few slashes to move from an absolute to a relative directory structure. As you can see from point 3 above, there are five slashes before the include directory, which a -p5 flag will get rid of for you.
$ cd [WORDPRESS DIRECTORY]
$ patch -p5 < changeset_40547.diff
After I did this my tests ran correctly again.
NOTICE: Command php bin/console generate:doctrine:crud also create TestController in src/Tests so it can throw error when you tried to start server if you don't have UnitTests. Remove the file fix it!
For me, it was because I ran
$ phpunit .
instead of
$ phpunit
when I already had a configured phpunit.xml file in the working directory.
I am using php 5.6 on window 10 with zend 1.12 version for me adding
require_once 'PHPUnit/Autoload.php';
before
abstract class Zend_Test_PHPUnit_ControllerTestCase extends
PHPUnit_Framework_TestCase
worked. We need to add this above statement in ControllerTestCase.php file