I am trying to mock a class for phpunit. Php unit fails with the error Could not load mock ... class already exists. This is the only test I'm running, so it can't be the case that the class is mocked already.
Any suggestion would be appreciated.
Here is the error case:
namespace Tests\Feature;
use Tests\TestCase;
class DeactivateACSTest extends TestCase
{
public function testDeactivateAcs()
{
$deviceController = \Mockery::mock('overload:App\Http\Controllers\Cloud\DeviceController');
$deviceController
->shouldReceive('deactivateACS')
->andReturn('hilfehilfehilfe');
$devCon = new \App\Http\Controllers\Cloud\DeviceController();
$this->assertEquals('hilfehilfehilfe', $devCon->deactivateACS());
}
}
When running it without --code-coverage it works:
[13:10:15] vagrant#homestead [~/Code/ekp] $ phpunit --filter DeactivateACS
PHPUnit 6.5.10 by Sebastian Bergmann and contributors.
==> Tests\Feature\DeactivateACSTest ✓
Time: 1.08 seconds, Memory: 16.00MB
OK (1 test, 3 assertions)
However, when running it with --code-coverage it fails:
[13:10:23] vagrant#homestead [~/Code/ekp] $ phpunit --coverage-html coverage --coverage-text=code_coverage.txt --filter DeactivateACSTest
PHPUnit 6.5.10 by Sebastian Bergmann and contributors.
==> Tests\Feature\DeactivateACSTest ⚈
Time: 5.79 seconds, Memory: 44.00MB
There was 1 error:
1) Tests\Feature\DeactivateACSTest::testDeactivateAcs
Mockery\Exception\RuntimeException: Could not load mock \App\Http\Controllers\Cloud\DeviceController, class already exists
/home/vagrant/Code/ekp/vendor/mockery/mockery/library/Mockery/Container.php:220
/home/vagrant/Code/ekp/vendor/mockery/mockery/library/Mockery.php:116
/home/vagrant/Code/ekp/tests/Feature/DeactivateACSTest.php:11
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
Generating code coverage report in HTML format ... done
You should add these annotations before the functions that are mocking this class.
/**
* #runInSeparateProcess
* #preserveGlobalState disabled
*/
For reference you can check out the phpunit documentation.
https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.runInSeparateProcess
https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.preserveGlobalState
I ran into the same issue and fixed like this:
There was another test in my unit tests (not mockery test) which had require_once on the PHP file that had the class I was mocking. I've removed that line.
I've added processIsolation="true" in test suite
Problem
I'm trying to setup a custom directory structure
for some shared classes in my Symfony project. I
want to create a custom folder in the root of my
project and I want to use the Symfony auto-load
feature to automatically register services from
that folder.
So I added a custom services namespace to the
services.yaml file:
# src ./config/services.yaml
services:
...
TestNamespace\:
resource: '../TestNamespace/*'
...
And I added an empty class in the custom folder:
# src ./TestNamespace/TestClass.php
namespace TestNamespace;
class TestClass
{
}
When I run the app I get the following error:
(1/2) InvalidArgumentException
Expected to find class "TestNamespace\TestClass" in file
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php"
while importing services from resource
"../TestNamespace/*", but it was not found! Check the
namespace prefix used with the resource.
(2/2) FileLoaderLoadException
Expected to find class "TestNamespace\TestClass" in file
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php" while
importing services from resource "../TestNamespace/*", but it was not
found! Check the namespace prefix used with the resource in
/path/to/ClassLoadErrorDemo/demo/config/services.yaml (which is loaded
in resource "/path/to/ClassLoadErrorDemo/demo/config/services.yaml").
I double checked the paths, namespace and the class
name multiple times and everything seems fine and I
don't understand why I still get the error.
Controllers in the ./src folder seem to load fine.
What am I doing wrong here?
Steps to reproduce
I created a demo repo to isolate the problem.
git clone https://github.com/smoelker/SymfonyClassLoadErrorDemo.git
cd SymfonyClassLoadErrorDemo/demo
composer install
mv TestNamespace/TestClass.php_ TestNamespace/TestClass.php
php bin/console server:start
Update your composer.json autoload setup
{
[...]
"autoload": {
"psr-4": {
"TestNamespace\\": "TestNamespace/",
"": "src/"
}
},
[...]
}
After run: composer dump-autoload and try again.
composer dump-autoload --classmap-authoritative will only work if your src directory is present at the time you run the command.
This can be an issue with multi-stage Docker builds in particular, when you are normally only copying the composer.json/composer.lock into the build image.
I've been trying to integrate Laravel Dusk into my testing scheme for a week and can't get any test to actually deliver expected results. Here's the situation:
I'm running Laravel 55 on Homestead (per Project install) with php 7.1.*
I installed Dusk following the installation steps in the docs.
Out of the box the tests didn't work
I added the steps found in this article on "Laravel Dusk on Homestead" and the gist found here in "setup-headless-selenium-xvfb.sh" this to my provisioning file. This removed a lot of the exceptions I was getting.
I also added all my existing environment vars to the php node of my phpunit.dusk.xml file exactly as they were done so in the already successfully running phpunit tests from phpunit.xml
However now when I run the tests I just can't get the expected output. This is what I am doing. I add an input field in my home page ('/') view file as such: <input id="dusk-test" value="1234">
I run this test which is a mod of the original example test and is the only test:
<?php
namespace Tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
class ExampleTest extends DuskTestCase
{
public function testBasicExample()
{
$this->browse(function (Browser $browser)
{
$browser->visit('/')->refresh()
->assertValue('#dusk-test', '1234')
;
});
}
}
...by running php artisan dusk and this is my output EVERY time
PHPUnit 6.4.3 by Sebastian Bergmann and contributors.
E 1
/ 1 (100%)
Time: 1.07 seconds, Memory: 12.00MB
There was 1 error:
1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\NoSuchElementException: no such element:
Unable to locate element: {"method":"id","selector":"dusk-test"}
(Session info: headless chrome=62.0.3202.62)
(Driver info: chromedriver=2.32.498513 (2c63aa53b2c658de596ed550eb5267ec5967b351),platform=Linux 4.4.0-92-generic x86_64)
/home/vagrant/landing/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:102 /home/vagrant/landing/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:320
/home/vagrant/landing/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:535
/home/vagrant/landing/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:175
/home/vagrant/landing/vendor/laravel/dusk/src/ElementResolver.php:281
/home/vagrant/landing/vendor/laravel/dusk/src/ElementResolver.php:327
/home/vagrant/landing/vendor/laravel/dusk/src/Concerns/MakesAssertions.php:632
/home/vagrant/landing/tests/Browser/ExampleTest.php:22
/home/vagrant/landing/vendor/laravel/dusk/src/TestCase.php:92
/home/vagrant/landing/tests/Browser/ExampleTest.php:24
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
To make this even more confusing, this is my output when I dump from the test. Here's how I dump
<?php
namespace Tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
class ExampleTest extends DuskTestCase
{
/**
* A basic browser test example.
*
* #return void
*/
public function testBasicExample()
{
$this->browse(function (Browser $browser)
{
$browser->visit('/')
->dump()
;
});
}
}
and my output after running php artisan dusk again is
PHPUnit 6.4.3 by Sebastian Bergmann and contributors.
"<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body></body></html>"
Which is absolutely NOT my homepage. I also dumped the $url value from vendor/laravel/dusk/src/Browser.php and got my projects correct APP_URL.
I'm at a loss. Dusk is being sent the right location and the page definitely has the input and value. But, I can't get Dusk to give the expected output which would be that 12345 was retrieved from the element.
All help appreciated.
maybe what i'm saying is wrong ... but Laravel dusk seems to need dusk instead of id: like dusk="dusk-test". also call it after :
$browser->visit('/')>refresh()
->assertValue('#dusk-test', '1234') and it should be like the doc.
On Github someone solved his problem by replacing https:// with http://
in the .env file.
I created a vendor library with this configuration:
"autoload": {
"psr-4": { "Company\\PhpUtils\\": "src/" }
},
Directory structure:
php-utils/
---src/
------JSON/
--------Json.php
Json Class:
<?php
namespace Company\PhpUtils\JSON;
Now I include it as a dependency:
"company/php-utils": "1.0.0"
and use it in a symfony test:
<?php
namespace Tests\AppBundle\Controller;
use Company\PhpUtils\JSON\Json;
Run tests:
./vendor/phpunit/phpunit/phpunit ./tests
PHPUnit 4.8.22 by Sebastian Bergmann and contributors.
PHP Fatal error: Class 'Company\PhpUtils\JSON\Json' not found in...
The class Json is static... well... follows singleton pattern.
So...Easy question. What am I doing wrong?
In your phpunit command there's no bootstrap, change from:
./vendor/phpunit/phpunit/phpunit ./tests
To:
./vendor/phpunit/phpunit/phpunit ./tests --bootstrap ./vendor/autoload.php
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