I have a Laravel app installed in my directory f:\lara_app. I use PHP artisan serve to run the app. I have Laravel version 5.4.36 (via Composer Install)
I am not trying my hand in using the PHP Unit to do testing. Inside f:/lara_app/tests/Unit/ExampleTest.php, I have the following codes:
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
public function myFirstTest()
{
$value = 'Hello World';
$this->assertTrue( 'Hello' === $value, 'Value should be Hello World');
}
}
I now try to run the test from my command prompt:
f:\lara_app> .vendor/phpunit/phpuni/phpunit
But I'm getting the message below:
'.vendor' is not recognized as an internal or external command, operable program or batch file
How do I run the PHPUnit test?
Thanks in advance
Use quotes:
"./vendor/bin/phpunit"
This should work on windows
f:\lara_app> php vendor/phpunit/phpunit/phpunit
This works for me
C:\code\project-name> vendor\bin\phpunit
For every Laravel project from version 7.x, if you want to run tests you can do one of these:
You can use artisan: php artisan test docs
Or you can use phpunit: if you want to run phpunit on windows, only by typing phpunit, you can create a bat file in your project's main directory by running this command:#echo php vendor\phpunit\phpunit\phpunit > phpunit.bat and then you can type phpunit in your command and enjoy.
Happy Testing...
Also for future readers, you can run it on windows powershell, without having to change anything, if you're in the root directory of your project. Simply Type
./vendor/bin/phpunit
Use quotes or use backslashes. Unlike linux, Windows does not like forward slashes.
Check if you have phpunit in composer.json, and run:
composer update
And then run PHPUnit:
vendor/bin/phpunit
Related
After I installed laravel-dusk following the official Laravel documentation and run this command:
php artisan make:component CardComponentTest
Then try to run immediately:
php artisan dusk tests/Browser/Components/CardComponentTest.php
I get this error:
Class 'Tests\Browser\Components\CardComponentTest' could not be found in '/var/www/html/tests/Browser/Components/CardComponentTest.php'.
I tested file and path are correct:
ls -l /var/www/html/tests/Browser/Components/CardComponentTest.php
And it says:
-rw-r--r-- 1 djw djw 6917 Dec 3 11:25 /var/www/html/tests/Browser/Components/CardComponentTest.php
So it is exists and readable.
I checked the namespace in the file:
<?php
namespace Tests\Browser\Components;
It also looks good.
I checked the composer.json and in this I have this section:
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
So the file exists, the namespace is good and the namespace is picked up in the composer.json.
I tried to run composer dump-autoload too. All good.
Any ide what's wrong whit this?
the error:
Class 'Tests\Browser\Components\CardComponentTest' could not be found in '/var/www/html/tests/Browser/Components/CardComponentTest.php'.
indicate you don't have CardComponentTest test case. Because CardComponentTest is not test case but just an component/part of test.
As aless said, component is not a test itself. But if you really want to test CardComponentTest you can replace
use Laravel\Dusk\Component as BaseComponent;
class CardComponentTest extends BaseComponent
to :
use Tests\DuskTestCase;
class CardComponentTest extends DuskTestCase
after you do that you can run php artisan dusk tests/Browser/Components/CardComponentTest.php , You just need to add test method first like. An example:
public function testComponentExample()
{
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertSee('Laravel');
});
}
But create test case in component folder is not best practice. You should create test case like official documentation said. Run dusk:make instead of dusk:component. An example:
php artisan dusk:make SimpleBrowserTest
and now you can run
php artisan dusk tests/Browser/SimpleBrowserTest.php
If you take a look at the documentation, the Component is not a test itself. Hence, you should not name the component "*Test" and you should not try to run the component like a dusk test.
You will use your component in your dusk test as described here:
https://laravel.com/docs/9.x/dusk#using-components
Components are for repeated actions, like selecting a date in a picker, which is then further used in your test case for example in a form or maybe some change in your UX happens that is assertable.
I created a new Symfony 4 project via symfony new my_project_name.
Currently when I execute ./bin/console, the output shows
I will create some custom console commands and I want show only my custom commands when I do ./bin/console
Maybe I should create a custom executable 'console' from scratch, but I don't know how do that.
You are creating a complete Symfony application, so all the commands provided by the included packages are available.
Instead of starting from a framework and trying to trim down the parts you do not want, you need to start from further down to have a really barebones project.
Bootstrapping the project:
First, do not use symfony command, no need. Plain old composer will do the trick.
On an empty directory, execute:
composer require symfony/console
This will import the only dependency needed for a console project, and do the basic bootstrapping for your autoloader.
In composer.json, add the following:
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
Command class
You'll need one or more commands to actually add to your application. Let's start with a fully fledged greeting application. Create the file src/Greet.php within your project:
declare(strict_types=1);
namespace App;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Greet extends Symfony\Component\Console\Command\Command
{
protected function configure()
{
$this->addArgument('person', InputArgument::OPTIONAL, 'Name of the Entity being greeted', 'World');
$this->addOption('greeting', 'g', InputOption::VALUE_OPTIONAL, 'How to greet the entity', 'Hello');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$greeting = $input->getOption('greeting');
$entity = $input->getArgument('person');
$output->writeln("<info>$greeting $entity!</info>");
}
}
This is a basic command that will print "Hello World!" if executed without any option or argument, will accept one argument use instead of "World", and one option to set the greeting instead of "Hello".
Console Application
On the project's root, create a file app.php.
require __DIR__ . '/vendor/autoload.php';
$app = new Symfony\Component\Console\Application('Hello World App', '1.0.0');
$app->add((new App\Greet('greet')));
$app->run();
This is be a very short script, so let's go line by line
Require the autoloader. This script is the entry point for the application, so we need to execute the autoloader.
Instantiate the application. This creates a new instance of the Symfony Console application, sets a name and version for the app. This will be used in the "help" printouts for the app.
Add the command. By default, the application has no commands at all. We'll need to add the command we have just created. add() expects a Command instance. We instantiate the command we just created, and we set it to be called by the name "greet".
Run the application
Generate autoloader.
Execute composer dump-autoload so the autoloader for your application is generated.
Execute the script.
If you now execute php app.php you'll get:
Hello World App 1.0.0
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
greet
help Displays help for a command
list Lists commands
Note that the only available command is greet. Which you can use like this:
# php app.php greet
Hello World!
# php app.php greet Alice
Hello Alice!
# php app.php greet Bob -g "Good morning"
Good morning Bob!
# php app.php help greet
Usage:
greet [options] [--] [<person>]
Arguments:
person Name of the Entity being greeted [default: "World"]
Options:
-g, --greeting[=GREETING] How to greet the entity [default: "Hello"]
[... default generic options omitted]
What I have:
WPKit/Module/AbstractFunctions.php Abstract Class;
wp-content/themes/mytheme/modules/quiz/Functions.php:
use WPKit\Module\AbstractFunctions;
class Functions extends AbstractFunctions { ... }
wp-content/themes/mytheme/tests/quiz/QuizFunctionsTest.php:
require_once dirname(__FILE__) . "/../../modules/quiz/Functions.php";
class QuizFunctionsTest extends TestCase {
public function testGetQuizByID() {
# some code
}
}
When running phpunit QuizFunctionsTest.php, it gives me the following error:
PHP Fatal error: Class '%path%\AbstractFunctions' not found in %path%/modules/quiz/Functions.php on line 18
I tried require_once the missing class but it didn't help. Outside the test class my code works just fine. Any thoughts?
TL;DR: It seems I couldn't get it to work because it was a WordPress setup so what I did was install PHPUnit via wget and use WP-CLI to scaffold theme-tests, then it worked like a charm.
First I installed the PHPUnit from terminal inside my theme directory:
wget -O phpunit https://phar.phpunit.de/phpunit-7.phar
chmod +x phpunit
Next I installed WP-CLI:
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp
Next setting up the test suite:
wp scaffold theme-tests your-theme-slug
Also make sure you have svn installed.
In my case (and I found some mention it, too) I had to delete /tmp/wordpress and /tmp/wordpress-tests-lib and re-run the previous command twice because the script somehow didn't download everything.
Notice that you'll have a separate WordPress setup in /tmp/wordpress. In my primary WordPress setup I use WPKit library which is stored in WordPress root near wp-content so I had to copy it to /tmp/wordpress, otherwise my PHPUnit tests couldn't find WPKit files which were included in the classes I had to test.
So when you run wp scaffold it creates bin directory in your theme root. Run the following command from your theme root in order to install the test suite:
bin/install-wp-tests.sh <test-database-name> <user> <password> <host> <wordpress-version>
In my case it looked like:
bin/install-wp-tests.sh wp_test root '' localhost latest
Be sure to use empty database because running PHPUnit clears the database every time so you may lose your data.
After all these actions just run PHPUnit and you should be fine:
./phpunit
It runs tests in your-theme/tests directory. By default it ignores the default test file so use it to make your own simple tests to check everything works.
Whew.
Sources:
https://www.kirstencassidy.com/testing-wordpress-plugins-wp-cli-phpunit/
https://phpunit.de/getting-started/phpunit-7.html
https://wp-cli.org/#installing
https://www.smashingmagazine.com/2017/12/automated-testing-wordpress-plugins-phpunit/
I am struggling to run a single test method named testSaveAndDrop in the file escalation/EscalationGroupTest.php with phpunit. I tried the following combinations:
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=escalation/EscalationGroupTest.php::testSaveAndDrop
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=EscalationGroupTest.php::testSaveAndDrop
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=EscalationGroupTest::testSaveAndDrop
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=testSaveAndDrop
In each case all test methode in the file escalation/EscalationGroupTest.php are executed. How to select just ONE method instead?
The name of the class is EscalationGroupTest and the version of phpunit is 3.2.8.
The following command runs the test on a single method:
phpunit --filter testSaveAndDrop EscalationGroupTest escalation/EscalationGroupTest.php
phpunit --filter methodName ClassName path/to/file.php
For newer versions of phpunit, it is just:
phpunit --filter methodName path/to/file.php
I prefer marking the test in annotation as
/**
* #group failing
* Tests the api edit form
*/
public function testEditAction()
Then running it with
phpunit --group failing
No need to specify the full path in the command line, but you have to remember removing this before commit, not to clutter the code.
You may also specify several groups for a single test
/**
* #group failing
* #group bug2204
*/
public function testSomethingElse()
{
}
Here's the more generic answer:
If you are sure the method name is unique you can only filter by method name (this works for me)
phpunit --filter {TestMethodName}
However it is safer to specify the file path/reference as well
phpunit --filter {TestMethodName} {FilePath}
Example:
phpunit --filter testSaveAndDrop reference/to/escalation/EscalationGroupTest.php
Quick note: I've noticed that if I have a function named testSave and another function named testSaveAndDrop using command phpunit --filter testSave will also run testSaveAndDrop and any other function that starts with testSave*, it's weird!!
Following command will execute exactly testSaveAndDrop test.
phpunit --filter '/::testSaveAndDrop$/' escalation/EscalationGroupTest.php
Run this inside your project root directory i am using in laravel root directory.
vendor/bin/phpunit --filter 'Your method name'
Example with custom method name.
/** #test //Initilize this for custom method name, without test keyword
*
* Test case For Dashboard When User Not logged In it will redirect To login page
*/
public function only_logged_in_user_see_dashboard()
{
$response = $this->get('/dashboard')
->assertRedirect('/login');
}
Example with test keyword
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
for run phpunit test in laravel by many way ..
vendor/bin/phpunit --filter methodName className pathTofile.php
vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName'
for test single class :
vendor/bin/phpunit --filter tests/Feature/UserTest.php
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest'
vendor/bin/phpunit --filter 'UserTest'
for test single method :
vendor/bin/phpunit --filter testExample
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample'
vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php
for run tests from all class within namespace :
vendor/bin/phpunit --filter 'Tests\\Feature'
for more way run test see more
So, something like this
phpunit --filter 'EscalationGroupTest::testSaveAndDrop' EscalationGroupTest escalation/EscalationGroupTest.php
Without = and with '
https://phpunit.de/manual/3.7/en/textui.html
If you're in netbeans you can right click in the test method and click "Run Focused Test Method".
You Can try this i am able to run single Test cases
phpunit tests/{testfilename}
Eg:
phpunit tests/StackoverflowTest.php
If you want to run single Test cases in Laravel 5.5 Try
vendor/bin/phpunit tests/Feature/{testfilename}
vendor/bin/phpunit tests/Unit/{testfilename}
Eg:
vendor/bin/phpunit tests/Feature/ContactpageTest.php
vendor/bin/phpunit tests/Unit/ContactpageTest.php
The reason your tests are all being run is that you have the --filter flag after the file name. PHPUnit is not reading the options at all and so is running all the test cases.
From the help screen:
Usage: phpunit [options] UnitTest [UnitTest.php]
phpunit [options] <directory>
So move the --filter argument before the test file that you want as mentioned in #Alex and
#Ferid Mövsümov answers. And you should only have the test that you want run.
Given that you
vendor/bin/phpunit --filter=EscalationGroupTest::testSaveAndDrop
If you're using an XML configuration file, you can add the following inside the phpunit tag:
<groups>
<include>
<group>nameToInclude</group>
</include>
<exclude>
<group>nameToExclude</group>
</exclude>
</groups>
See https://phpunit.de/manual/current/en/appendixes.configuration.html
I am late to the party though. But as personal I hate to write the whole line.
Instead, I use the following shortcuts in the .bash_profile file make sure to source .bash_profile the file after adding any new alias else it won't work.
alias pa="php artisan"
alias pu="vendor/bin/phpunit"
alias puf="vendor/bin/phpunit --filter"
Usage:
puf function_name
puf filename
If you use Visual Studio Code you can use the following package to make your tests breeze.
Package Name: Better PHPUnit
Link: https://marketplace.visualstudio.com/items?itemName=calebporzio.better-phpunit
You can then set the keybinding in the settings. I use Command + T binding in my MAC.
Now once you place your cursor on any function and then use the key binding then it will automatically run that single test.
If you need to run the whole class then place the cursor on top of the class and then use the key binding.
If you have any other things then always tweek with the Terminal
Happy Coding!
You must use --filter to run a single test method
php phpunit --filter "/::testMethod( .*)?$/" ClassTest ClassTest.php
The above filter will run testMethod alone.
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