Run unit test when saving file in PhpStorm - php

I have set up PhpStorm 5 with PHPUnit, and I'm curious if PhpStorm might have some functionality that will automatically run a unit test when saving a file. Like watchr and guard. I have tried search our beloved www and the PhpStorm docs, but haven't been able to find a solution for it.

As of version 6, PHPStorm has "File Watchers"
Open your project preferences.
Select File Watchers from the left hand list of options.
Click the + symbol at the bottom of the empty right hand panel.
Select <custom>
You will have to set up a command line for PHPUnit, it wont be the integrated testing, but you can have errors output to the console (which is good a good start!)
Various macro options are available to you, so you can include (for example) $FileNameWithoutExtension$Test.php in the arguments passed to your command line.
I personally had to set up two watchers. The first detected modifications to project files, and the second detected changes to test files (the second did not append Test.php to the filename) I also created a new project scope to exclude the tests directories from the first watcher.
You may also want to turn off immediate synchronisation, as this causes PHPUnit to run when PHPStorm auto-saves files.
My other settings are like:
File Type: PHP files (PHP)
Scope: Project excluding tests
Program: /path/to/php
Arguments: /path/to/phpunit --configuration /path/to/phpunit.xml.dist /path/to/tests/$FileNameWithoutExtension$Test.php
Working directory: $FileDir$
Output paths: $FileDir$
No output filters set, syntax error checks enabled, and console showing errors.

PHPUnit watcher named as hot phpunit runner
https://github.com/slavahatnuke/hot-phpunit-runner

You can also have a look at TDDRunner
It is console tool that execute PHPUnit autmaticly on file changes. You can also configure PHPUnit by excuting only one file ot whatever.
/usr/bin/tddrunner --group=test
There's a a German article providing further detail.

In 2017 Jetbrains release a feature that allow auto-run for tests.
It's located in the Run console, therefore it's linked to the run settings, easing the setup of this autorun.
See https://blog.jetbrains.com/phpstorm/2017/07/autorun-phpunit-tests-in-phpstorm-2017-2/

Related

How do I set the working directory for phpunit using the XML file?

I'm looking through the documentation, but I'm not seeing any option to change the working directory used when running tests.
I'm using PhpUnit as it's included in Laravel. I want to be able to run vendor/bin/phpunit from my project's root directory, and have it run using the /public directory as the working directory.
I tried running ../vendor/bin/phpunit from the /public, but since the phpunit.xml file isn't in the public directory and I don't want to specify my config file path every time, that won't work.
Is there something I can add to my phpunit.xml file to tell it to run tests using the /public directory as the "cwd" (current working directory)?
Based on the feedback I received in the comments and the documentation, I determined the following:
It's probably not possible to change the cwd that phpunit uses by default (well, it's possible in PhpStorm, but not the command line without writing some kind of wrapper script)
Code that depends on being run from a specific directory is not a good idea.
What I had was some code in one of my classes like this:
$var = file_get_contents("../some_file.json");
This works fine -- until you try to add unit tests. The web server runs using the /public directory as the cwd, while phpunit will run using the root directory.
Rather than trying to force phpunit to always use a particular cwd (/public), I decided it's probably best to remove relative paths from the code that rely on a consistent cwd. So the line above becomes:
$var = file_get_contents(base_path("some_file.json"));
I didn't want to change production code that was already working just to get some tests in place, but this change seemed insignificant enough. (and it's an improvement anyway)
Well, you'd have to do the actual chdir in PHP, but you can define a bootstrap script in the XML (<phpunit bootstrap="./bootstrap.php">) and have that change the working directory.
Alternatively, you can put a setUpBeforeClass function into your test class that changes the working directory.

realpath() doesnt show realpath GitLab ci runner

the code is stored in /var/www/abc -- "CodePath"
when running gitlab-ci (runner), the code is called via /home/gitlab-runner/builds/4v8bC1n9/0/_gitlabgroup_/_gitprojectname_/abc -- "RealPath"
I'm using a local runner and a shell execution.
when I use the realpath() function in my php code, it still shows the "CodePath" when using gitlab ci runner, instead of "RealPath".
How can I get the "RealPath" integrated in my code, or reconfig GitLab to use the "CodePath" instead?
The runner cli options are documented here: https://docs.gitlab.com/runner/executors/shell.html#overview
The path where the job is run and your sources are cloned into is available in the environment variable:
CI_PROJECT_DIR
The full path where the repository is cloned and where the job is run. If the GitLab Runner builds_dir parameter is set, this variable is set relative to the value of builds_dir. For more information, see Advanced configuration for GitLab Runner.
You did no state how you use realpath(path)...
Whilst a path must be supplied, the value can be an empty string. In this case, the value is interpreted as the current directory.
So maybe you hardcode chdir('/var/www/abc'); somewhere?
When you do chdir(getenv('CI_PROJECT_DIR')); before you call realpath() - it should use the CI directory. Assuming you use realpath without a parameter.
Also: maybe you can make some changes and use one of the the built in constants for the current directory: https://www.php.net/manual/en/language.constants.predefined.php
Thanks to madflow's mentioning of the variable I managed to figure out the following:
runners specific configuration files exist and can be configured as described here
I needed to do these things:
specify enable the [runners.custom_build_dir] section in the config.toml
[[runners]]
builds_dir = "/var/www/abc"
[runners.custom_build_dir]
enabled = true
(boolean not in quotes)
specify a variable in my yml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/
on os level there was some privilege setting for the dir required, where I went for quick and dirty 777 on my local machine

Can't get Symfony 2 to work with PHPstorm

I've installed the symfony plugin to PHPstorm, but when I'm trying to run the project I get the following error
Fatal error: Class 'Doctrine\Tests\Common\Cache\CacheTest' not found in ...
I've checked the path and CacheTest file is in the correct folder. When I run the symfony project from the command line it works just fine.
Is there someway to fix this problem?
What you try is not correct. You execute the php.exe and that is the normal PHP executable. To run your Unit-Tests you need PHPUnit to run.
Go to Preferences -> Languages & Frameworks -> PHP -> PHPUnit and define the phpunit.phar.
When you've done that you create a new configuration to run PHPUnit and you define the configuration which is under app/phpunit.xml.
I figured it out. First of all you need add phpunit.phar as Stony explained in his answer.
After that all I really needed to do was to rename phpunit.xml.dist to phpunit.xml in app/ folder and then just right click it and choose the Run 'phpunit.xml' option. This way the Tests succeed and it doesn't give any errors.
As for running the symfony project you need to add symfony command line tool support to phpstorm. All about that in this link: https://confluence.jetbrains.com/display/PhpStorm/Symfony2+Command+Line+Tool+Integration+-+Symfony+Development+using+PhpStorm
After that you just run it as a command like you would with normal command line. That's also explained in the link.
Try to choose "Use custom autoloader" option in Preferences -> Languages & Frameworks -> PHP -> PHPUnit and specify the path to vendor/autoload.php file.

Not able to run codecoverage with PhpStorm

I am trying to run unit test in PhpStorm with codecoverage.
It throws me a error msg saying interpreter is missing. How to install the interpreter!
Also how to configure in order to run my tests with code coverage.
Steps to do:
1. Set interpreter and language level.
File -> Settings -> Languages & Frameworks -> PHP
Select your PHP version. Then click button with ... (three dotes), then add interpreter.
https://www.jetbrains.com/phpstorm/help/interpreters.html
2. Add PHPUnit to project.
File -> Settings -> Languages & Frameworks -> PHPUnit
a) Load form include path
To add this you must set where PHPUnit library is installed. Then add using External Libraries in Project.
To specify path use green + button.
b) Use custom autoloader
Use this option when you install PHPUnit via composer. In Path to script field specify autoload file.
https://www.jetbrains.com/phpstorm/help/phpunit.html
3. Configure tests
In the top right corner use Select Run/Debug Configuration menu
And click Edit Configurations. Select green + button to add PHPUnit.
Define name of the configuration and directory with tests. Additionally you can add some PHPUnit arguments in Test Runner options field.
https://www.jetbrains.com/phpstorm/help/run-debug-configuration-phpunit.html
Annotation 1 - Configure bootstrap
Tests sometimes needs to use a bootstrap file which set environments, loads configs etc. To set this file go to:
File -> Settings -> Languages & Frameworks -> PHPUnit
and select the bootstrap file in Default bootstrap file field.
https://www.jetbrains.com/phpstorm/help/phpunit.html - in Bootstrap file section.
Annotation 2 - Run tests with code coverage
To run with coverage you must install Xdebug PHP extension. You should read the Xdebug installation guide.
After this actions use a icon
to run with coverage.
https://www.jetbrains.com/phpstorm/help/code-coverage.html

Is it possible to run HTML test suite from PHPUnit?

I want to measure code coverage of an HTML test suite for selenium. Therefore I want to use PHPUnit in order to execute the suite, because PHPUnit has nice support for code coverage analysis.
Therefore: Is it possible to run an HTML test suite from PHPUnit?
Short answer
Running individual HTML test files is not a problem, running HTML suites files however does not seem to work. As long as you put all the HTML test files from a suit in a directory by themselves you can just run runSelenese($folderName)
Long answer
I had no idea that running Selenium HTML files directly was even possible until I did some more digging.
What I used to do is convert/export them first with the Selenium IDE PHP Formatter plugin for Firefox.
Apparently this is not necessary. All the way at the bottom of Chapter 17. PHPUnit and Selenium the manual states:
Using the runSelenese($filename) method, you can also run a Selenium test from its Selenese/HTML specification. Furthermore, using the static attribute $seleneseDirectory, you can automatically create test objects from a directory that contains Selenese/HTML files. The specified directory is recursively searched for .htm files that are expected to contain Selenese/HTML. Example 17.5 shows an example.
Example 17.5: Use a directory of Selenese/HTML files as tests
<?php
require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
class SeleneseTests extends PHPUnit_Extensions_SeleniumTestCase
{
public static $seleneseDirectory = '/path/to/files';
}
?>
Once you have your Tests in PHPUnit you can use it to get code coverage from the Selenium Server.
Again, from the manual:
PHPUnit_Extensions_SeleniumTestCase can collect code coverage
information for tests run through Selenium:
Copy PHPUnit/Extensions/SeleniumTestCase/phpunit_coverage.php into your webserver's document root directory.
In your webserver's php.ini configuration file, configure PHPUnit/Extensions/SeleniumTestCase/prepend.php and PHPUnit/Extensions/SeleniumTestCase/append.php as the auto_prepend_file and auto_append_file, respectively.
In your test case class that extends PHPUnit_Extensions_SeleniumTestCase, use
protected $coverageScriptUrl = 'http://host/phpunit_coverage.php';
to configure the URL for the phpunit_coverage.php script.
As this can be a bit of a hassle to set up, I've always just used the Page Coverage plugin to get an insight into HTML page coverage.
Unit testing PHP HTML output is a great idea. More people should do it, but turns out it has not been that simple in the past.
I had the same problem and can up with this: https://packagist.org/packages/phpfui/html-unit-tester It can validate HTML and CSS from a URL, file, or string snippet.
To do what you want, you should set up a local web server that your tests can hit for your application. You probably have this already, but make sure it works for your local env and any server you run tests on.
Then you can use the assertValidUrl method with a path to your local server. Since you are not comparing to a template, but just testing that the HTML is valid, you can quickly find recently introduced HTML errors.
Hope this helps.

Categories