'PHP Fatal error: Class not found - PHPUnit
I'm trying to use PHPUnit in a PHP project. Here is my project structure (files are in italic font style)
controllers
- Pages.php
tests
- pagesTest.php
vendor
- bin
- phpunit.bat
- bin
composer.json
My files:
composer.json
{
"require-dev": {
"phpunit/phpunit":"5.5.4"
}
}
Pages.php
<?php
namespace controllers
class Pages
{
public function render()
{
return 'Hello World';
}
}
pagesTest.php
<?php
class PagesTest extends PHPUnit_Framework_TestCase
{
public function testRenderReturnsHelloWorld()
{
$pages = new \controllers\Pages();
$expected = 'Hello Word';
$this->assertEquals($expected, $pages->render());
}
}
When I open the command line I write:
C:\xampp\htdocs\PHPUnitTestProject\vendor\bin>phpunit ../../tests/PagesTest.php
I receive this error message: PHP Fatal error: Class 'controllers\Pages' not found in C:\xampp\htdocs\PHPUnitTestProject\tests\pagesTest.php on line 7
It's a path problem. I think it's because it searches for C:\xampp\htdocs\PHPUnitTestProject\vendor\bin\controllers\Pages()
which doesn't exists.
It should be C:\xampp\htdocs\PHPUnitTestProject\controllers\Pages()
Solution 1:[1]
You need to point to the tested class, so in pagesTest.php add a require:
require __DIR__ . "/../controllers/Pages.php";
Or if you are using autoloading, then you can bootstrap the autoload in your command line
phpunit --bootstrap src/autoload.php
Or you can set up a phpunit.xml configuration file like this example (from the PHPUnit page I linked to above):
<phpunit bootstrap="src/autoload.php">
<testsuites>
<testsuite name="money">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
Which you then use with the --configuration option.
Solution 2:[2]
Adding bootstrap="vendor/autoload.php"
in phpunit.xml.dist solved the issue for me.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"> <!-- in here -->
<php>
<!-- ... -->
</php>
<testsuites>
<!-- ... -->
</testsuites>
</phpunit>
Solution 3:[3]
Try composer dump-autoload -o
command
Solution 4:[4]
Call phpunit
from the root folder:
$ cd C:\xampp\htdocs\PHPUnitTestProject\
$ vendor\bin\phpunit tests/PagesTest.php
Solution 5:[5]
I was getting the same error because I hadn't named my Class the same as the filename that phpunit was calling.
e.g. I was calling:
phpunit TEST_myweb_controller.php
which had a class definition of: class web_controller_test extends PHPUnit\Framework\TestCase
This returned error: Class 'TEST_myweb_controller.php' could not be found in '\my\path\to\tests\TEST_myweb_controller.php'
To fix this I changed the class deinition to: class TEST_myweb_controller extends PHPUnit\Framework\TestCase
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Katie |
Solution 2 | Allen |
Solution 3 | zlatan |
Solution 4 | JorgeObregon |
Solution 5 | GreensterRox |