Установка PHPUnit.

Существует несколько способов установки PHPUnit — фреймворка для модульного тестирования скриптов языка PHP.
Страница официальной документации по установке PHPUnit на английском языке: https://phpunit.de/manual/current/en/installation.html
Рассмотрим способы установки подробно.
1. Composer
Довольно простой и в настоящее время оптимальный способ — с помощью менеджера зависимостей для PHP — Composer. Более-менее большой проект, как правило, использует данный инструмент, к тому же Composer имеет автозагрузчик который удобно использовать и для подключения тестируемого кода.
Узнать текущую версию PHPUnit можно тут. В примерах установки мы будем устанавливать версию 5.7. Более поздние версии требуют наличия PHP 7+ А PHPUnit 5.7 поддерживается на PHP 5.6, PHP 7.0 и PHP 7.1
Итак, команда для Composer устанавливающая PHPUnit версии 5.7 :
Если нужно — расширение для тестов с базой данных
Установив можно запустить тестирование командой из корня проекта:
тут имеется ввиду, что тесты будут храниться в папке tests , расположеной в корне приложения на уровне файла composer.json в противном случае нужно указать другой путь к папке с тестами.
Чтобы не набирать каждый раз строку vendor\bin\phpunit, можно:
1) Если нужно только для текущего проекта — создать файл phpunit.bat в корневой папке приложения с содержимым:
После этого можно будет запускать тестирование так:
2) Установить phpunit глобально, чтобы вызывать простой командой (phpunit) из любой директории любого проекта:
Это установит phpunit в директорию текущего пользователя, например:
C:\Users\username\AppData\Roaming\Composer\vendor
и сохранит запускающий файл в папке vendor\bin пользователя. Далее нужно прописать путь к этому файлу в системную переменную PATH (если нет еще), добавить путь к папке bin:
где username заменить на имя пользователя.
Если файл, методы которого хотим протестировать, не подключаются автоматически в тестирующем его классе, то нужно сделать это самостоятельно. Т.к. используется Composer, то делать это лучше всего с помощью его автозагрузчика. Для этого нужно отредактировать объект «autoload» в файле composer.json. Например кое-где для демонстрации тестирования я классам присвоил пространство имен main, а сами файлы положил в корень проекта. В таком случае получилось:
Теперь классы с пространством имен «main» автоматически будут найдены в корне проекта.
Или, например, создал в корне каталог app с файлами классов, которые нужно тестировать. Для того, что бы эти классы автоматически подключались нужно прописать:
После внесения изменений в composer.json нужно обновить автозагрузчик:
Если PHPUnit устанавливался глобально, то предварительно нужно подключить автозагрузчик приложения (обычно это автозагрузчик Composera), чтобы файлы классов, которые нужно протестировать, автоматически подключались в классах тестов. PHPUnit позволяет выполнить определенный код, а в данном случае загрузить автозагрузчик Composera до выполнения тестирования с помощью параметра bootstrap, который должен указывать на файл подключающий этот автозагрузчик и/или что-то еще.
Параметр bootstrap можно:
1) указывать в командной строке при вызове phpunit:
или можно подключить сразу автозагрузчик Composera напрямую:
2) указать в конфигурационном файле phpunit.xml:
или, если нужно только лишь подключить автозагрузчик Composera:
Если указываем подключение файла bootstrap.php, то создаем его в папке tests:
теперь классы приложения будут подключены.
Если при создании приложения не используется php-фреймворк, а PHPUnit установлен не глобально (в папку vendor проекта) — не забываем сами подключить автозагрузчик Composer в «точке входа», обычно это index.php
тут рассчитано, что индексный файл у вас находится на уровне каталога vendor (который появляется после использования Composer), т.е., возможно, понадобится подняться на уровень-два выше к данному каталогу.
Используя Composer вам не придется использовать аналогичную конструкцию типа require для подключения тестируемого класса, как это часто указано в примерах использования PHPUnit в интернете.
Осталось добавить, что при написании тестов в PHPUnit установленного с помощью Composer , ваш тестирующий класс (содержащий тесты) должен наследовать от класса phpunit:
2. Ручная установка
2.1 Установка вручную для Windows.
Скачать файл с последней версией PHPUnit https://phar.phpunit.de/phpunit.phar
Последний релиз требует PHP 7+, чтобы получить поддержку PHP 5.6, скачать:
https://phar.phpunit.de/phpunit-5.7.17.phar
Устанавливать будем в папку с php. При этом путь к интерпретатору php должен быть прописан в системную переменную PATH.
Итак, поместить файл в каталог с интерпретатором php (где находится файл php.exe), например W:\modules\php\PHP-5.6.
Перейти в каталог с PHP.exe, например у меня на OpenServere:
создать файл phpunit.bat в данном каталоге, чтобы получить доступ к phpunit из любой папки (например из корня своего приложения), а не только находясь в папке с php куда он установлен:
где вместо 5.7.17 указать версию скачанного файла.
Или так:
Проверим появился ли доступ:
Файл с тестируемым классом нужно подключить в классе который его будет тестировать:
или использовать автозагрузчик классов. Можно так же для автозагрузки подключить и использовать Composer, правда в таком случае проще и установку phpunit делать с его же помощью.
Тестирующий класс (содержащий тесты) должен наследовать от класса phpunit:
2.2 Установка вручную для Linux.
Делаем согласно документации https://phpunit.de
Тут первой строкой скачиваем файл с phpunit, далее даем файлу права на запуск b потом переименовываем файл phpunit-5.7.phar в phpunit для удобства.
Так же можно скачать самую последнюю версию phpunit командой:
После установки проверяем phpunit командой:
3. Установка с помощью PEAR
PEAR — это предшественник Composer , репозиторий PHP-классов . В настоящее время в данном репозитории находится устаревшая версия PHPUnit, тем не менее опишу и данный способ установки данного фреймворка для тестирования.
Прежде всего нужно установить (активировать) PEAR.
Опишу установку для Open Server, он содержит в себе все необходимые компоненты для этого.
В папке с интерпретатором php (например W:\modules\php\PHP-5.6) находится файл go-pear.bat и папка PEAR.
Для установки перейти из командной строки в корень папки php:
выполнить файл go-pear.bat, для этого набрать в консоли:
выбрать в диалогах:
(system|local) [system] : local
Please confirm local copy by typing ‘yes’ : yes
нажать Enter
Would you like to alter php.ini <W:\modules\php\PHP-5.6\php.ini>? [Y/n] : y
нажать Enter
проверить установился ли PEAR:
Теперь устанавливаем PHPUnit:
проверить появился ли доступ:
Тестирующий класс (содержащий тесты) должен наследовать от класса phpunit:
PHPUnit
PhpStorm supports unit testing of PHP applications through integration with the PHPUnit testing framework.
Before you start
Make sure the PHP interpreter is configured in PhpStorm on the PHP page, as described in Configure local PHP interpreters and Configure remote PHP interpreters.
Download and install PHPUnit
Before you start, make sure Composer is installed on your machine and initialized in the current project as described in Composer dependency manager.
Download and install phpunit.phar manually
Download phpunit.phar from the PHPUnit Official website and save it on your computer:
If you need full coding assistance in addition to the ability of running PHPUnit tests, store phpunit.phar under the root of the project where PHPUnit will be later used.
If you only need to run PHPUnit tests and you do not need any coding assistance, you can save phpunit.phar outside the project.
Download and install phpunit.phar with Composer
Inside composer.json , add the phpunit/phpunit dependency record to the require or require-dev section. Press Ctrl+Space to get code completion for the package name and version.
Do one of the following:
Click the Install shortcut link on top of the editor panel.
If the Non-installed Composer packages inspection is enabled, PhpStorm will highlight the declared dependencies that are not currently installed. Press Alt+Enter and select whether you want to install a specific dependency or all dependencies at once.
Click next to the package record in the composer.json editor gutter to jump to the corresponding Settings page and configure PHPUnit manually.
Integrate PHPUnit with a PhpStorm project
If you use a local PHP interpreter, PhpStorm performs initial PHPUnit configuration automatically. In the case of remote PHP interpreters, manual PHPUnit configuration is required.
Configure PHPUnit automatically
Store the phpunit.xml or phpunit.xml.dist configuration file under the project root.
PhpStorm will create the local framework configuration on the Test Frameworks page and the PHPUnit run/debug configuration.
Configure PHPUnit manually
In the Settings dialog ( Ctrl+Alt+S ), go to PHP | Test Frameworks .
On the Test Frameworks page that opens, click in the central pane and choose the configuration type from the list:
In local configurations, the default project PHP interpreter is used, see Default project CLI interpreters for details.
To use PHPUnit with a remote PHP interpreter, choose one of the configurations in the dialog that opens:
In the right-hand pane, choose the PHPUnit library installation type:
To use Composer autoloader, specify the path to the autoload.php file in the vendor folder. See Composer for details.
To run PHPUnit from phpunit.phar , download phpunit.phar, save the archive in the project root folder, and specify the path to it. For local configurations, you can download the archive by clicking the provided download link. To use it in the current project, make sure a default PHP interpreter is defined.
When you click , PhpStorm detects and displays the PHPUnit version.
In the Test Runner area, appoint the configuration XML file to use for launching and executing scenarios.
By default, PHPUnit looks for a phpunit.xml or phpunit.xml.dist configuration file in the project root folder. You can appoint a custom configuration file.
You can also type the path to a bootstrap file to have a PHP script always executed before launching tests. In the field, specify the location of the script. Type the path manually or click and select the desired folder in the dialog that opens.
Note that you can also provide an alternative configuration and bootstrap file when editing a PHPUnit run/debug configuration.
Generate a PHPUnit test for a class
Open the Create New PHP Test dialog by doing any of the following:
From the main menu, choose File | New . Then, choose PHP Test | PHPUnit Test from the context menu.
In the Project tool window, press Alt+Insert or right-click the PHP class to be tested and choose New | PHP Test | PHPUnit Test .
In the editor of the PHP class to be tested, position the caret at the definition of the class. Then, press Alt+Enter and select Create New Test from the popup menu. This way, you can generate a test for a PHP class defined among several classes within a single PHP file.
To create a test for a certain method, position the caret within the method declaration. The chosen method will be automatically selected in the methods list of the Create New PHP Test dialog.
The Create New PHP Test dialog opens.

Provide the parameters of the generated test:
The test file template, that is, the template based on which PhpStorm will generate the test class. Make sure that PHPUnit<6 is selected in the Test file template list.
The name of the test class. PhpStorm automatically composes the name from the production class name as <production class>Test.php .
The folder for the test class file, which is automatically suggested based on the containing directory and namespace of the production class, the configured test sources root and its psr-4 package prefix, or the directory value specified in the phpunit.xml configuration file.
To specify a different folder, click next to the Directory field and choose the relevant folder.
The namespace the test class will belong to, which is automatically suggested based on the containing directory and namespace of the production class, the configured test sources root and its psr-4 package prefix.
The production class methods to generate test method stubs for. Select the checkboxes next to the required production class methods. To include inherited methods from parent classes, select the Show inherited methods checkbox.
PhpStorm will automatically compose the test methods’ names as test<production method> . You can customize the code templates used for generating test method stubs on the Code tab of the File and Code Templates settings page.
After the test is created, you can navigate back to the production class by choosing Navigate | Go to Test Subject . For details, see Navigate between a test and its test subject.
If you are relying on the PHPUnit configuration file for providing the containing folder and namespace for the test class, make sure that it is selected on the Test Frameworks page as described in Integrating PHPUnit with a PhpStorm project.
Generate PHPUnit test methods
Open the required test class in the editor and position the caret anywhere inside the class definition.
Choose Generate in the context menu or press Alt+Insert . Then choose Test Method from the Generate list.
Set up the test fixture , that is, generate stubs for the code that emulates the required environment before test start and returns the original environment after the test is over:
Choose Generate in the context menu or press Alt+Insert . Then choose SetUp Method or TearDown Method from the Generate list.
You can customize the code templates used for generating PHPUnit test methods on the File and Code Templates page of the Settings dialog ( Ctrl+Alt+S ). To quickly access this page, in the Generate list, select Edit Template from the submenu of a method.

Run and debug PHPUnit tests
You can run and debug single tests as well as tests from entire files and folders. PhpStorm creates a run/debug configuration with the default settings and launches the tests. You can later save this configuration for further reuse.
Run or debug PHPUnit tests
In the Project tool window, select the file or folder to run your tests from and choose Run ‘<file or folder>’ or Debug ‘<file or folder>’ from the context menu of the selection:

PhpStorm generates a default run configuration and starts a run or debug test session with it.
Run or debug a single test
You can run or debug a single test for a specific test class or test method from the file editor window.
Open the test file in the editor, click the gutter icon next to the test and choose Run ‘<test_name>’ or Debug ‘<test_name>’ from the context menu. Alternatively, place the caret at the corresponding line and press Ctrl+Shift+F10 .
Run a test for a single data set
If the PHPUnit test uses a data provider, you can run single tests for some types of data sets. Data sets that can be run separately are marked with the gutter icon in the editor.
In the file editor, click in the gutter next to the data set (or right-click the corresponding code line) and select Run ‘<test_name>’ .
Run a selection of tests
Open the target file in the editor, right-click the desired test target, that is, a class or a method being tested, and either choose Go To | Test or press Ctrl+Shift+T .
From the popup menu, select the tests to be executed. For multiple selection use Ctrl and Shift .
Press Ctrl+Shift+F10 to run the tests selection.
After a test session is over, PhpStorm automatically creates a run/debug configuration with its Test scope set to Composite . See PHPUnit for details.
Save an automatically generated default configuration
After a test session is over, choose Save <default_test_configuration_name> from the context menu of the file or folder.
Run or debug tests through a previously saved run/debug configuration
Choose the required PHPUnit configuration from the list on the toolbar and click or .
Create a custom run/debug configuration
In the Project tool window, select the file or folder with the tests to run and choose Create run configuration from the context menu. Alternatively, choose Run | Edit Configurations from the main menu, then click and choose PHPUnit from the list.
In the PHPUnit dialog that opens, specify the scenarios to run, choose the PHP interpreter to use, and customize its behavior by specifying the options and arguments to be passed to the PHP executable.
Run PHPUnit tests in parallel
To speed up execution of PHPUnit tests in PhpStorm, you can run them in parallel processes using the ParaTest package. The parallel execution option can be set for PHPUnit tests that are grouped in folders (test suites).
Set the path to the ParaTest binary file for PhpStorm in the Test Runner settings by either of the following ways:
In the Settings dialog ( Ctrl+Alt+S ), go to PHP | Test Frameworks and set the Default ParaTest binary field.
For existing run configurations, open the Run Configuration dialog, select the Use ParaTest checkbox and set the path to the file in the field.
If you have ParaTest configured and installed together with PHPUnit in the compose.json file, the path to the ParaTest binary will be set automatically in the run configurations and settings. However, you still need to select the Use ParaTest checkbox to enable the parallel test run configuration.
In the Project tool window, right-click the folder to run the tests from and select the Run <test_name> (PHPUnit) with ParaTest option from the context menu.

Alternatively, right-click the phpunit.xml config file and select the Run `phpunit.xml (PHPUnit)` with ParaTest option from the context menu.
Monitor test results
PhpStorm shows the tests execution results in the Test Runner tab of the Run tool window.

The tab is divided into 2 main areas:
The left-hand area lets you drill down through all unit tests to see the succeeded and failed ones. You can filter tests, export results, and use the context menu commands to run specific tests or navigate to the source code.
The right-hand area displays the raw PHPUnit output.
Run PHPUnit tests automatically
You can have PhpStorm re-run tests automatically when the affected code is changed. This option is configured per run/debug configuration and can be applied to a test, a test file, a folder, or a composite selection of tests, depending on the test scope specified in this run/debug configuration.
On the Test Runner tab, press the toggle button on the toolbar:
Optionally, click the button and set the time delay for launching the tests upon the changes in the code:
Name already in use
phpunit-documentation-russian / src / installation.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
PHPUnit |version| требует PHP 7.2; настоятельно рекомендуется использовать последнюю версию PHP.
PHPUnit требует расширений dom и json, которые обычно включены по умолчанию.
PHPUnit также требует расширений pcre, reflection и spl. Эти стандартные расширения включены по умолчанию и не могут быть отключены без внесения изменений в систему сборки PHP и/или в исходный код C.
Для функциональности отчёта по покрытию кода тестами требуются расширения Xdebug (2.7.0 или новее) и tokenizer. Генерация XML-отчётов требует расширения xmlwriter.
PHP Archive (PHAR)
Самый простой способ получить PHPUnit — загрузить PHP Archive (PHAR), в котором есть все необходимые (а также некоторые необязательные) зависимости PHPUnit, собранные в одном-единственном файле.
Расширение phar обязательно для использования PHP Archives (PHAR).
Если расширение Suhosin включено, вам необходимо разрешить выполнение PHAR в вашем php.ini :
PHAR с PHPUnit можно использовать сразу после загрузки:
Как правило, далее необходимо сделать исполняемым PHAR-файл:
Проверка релизов PHPUnit PHAR
Все официальные релизы кода, распространяемые проектом PHPUnit, подписываются релиз-менеджером. Подписи PGP и хеши SHA256 доступны для проверки на phar.phpunit.de.
В следующем примере показано, как работает проверка релиза. Мы начинаем с загрузки :file:`phpunit.phar` , а также его отделённой подписи PGP :file:`phpunit.phar.asc` :
Мы хотим проверить PHP Archive ( :file:`phpunit-x.y.phar` ) PHPUnit с его отделённой подписью ( :file:`phpunit-x.y.phar.asc` ):
У нас нет открытого ключа релиз-менеджера ( 6372C20A ) в нашей локальной системе. Для продолжения проверки нам нужно получить открытый ключ релиз-менеджера с сервера ключей. Один из таких серверов — это :file:`pgp.uni-mainz.de` . Серверы открытых ключей связаны между собой, поэтому вы можете подключиться к любому из них.
Теперь мы получили открытый ключ для сущности, известной как «Sebastian Bergmann <sb@sebastian-bergmann.de>». Однако, у нас нет способа проверить, что этот ключ был создан человеком под именем Себастьян Бергман (Sebastian Bergmann). Но давайте снова попробуем проверить подпись релиза.
В данный момент подпись хорошая, но мы не доверяем этому ключу. Хорошая подпись означает, что файл не был изменён. Однако ввиду характера криптографии открытого ключа вам необходимо дополнительно проверить, что ключ 6372C20A был создан настоящим Себастьяном Бергманом.
Любой злоумышленник может создать открытый ключ и загрузить его на серверы открытых серверов. Затем они могут создать вредоносный релиз, подписанный этим поддельным ключом. После чего, если вы попытаетесь проверить подпись этого испорченного релиза, проверка будет успешной, потому что ключ не является «реальным» ключом. Поэтому вам нужно проверить подлинность этого ключа. Однако проверка подлинности открытого ключа выходит за рамки данной документации.
Проверка подлинности и целостности PHAR с PHPUnit вручную через GPG утомительна. Вот зачем нужен PHIVE (PHAR Installation and Verification Environment), среда установки и проверки PHAR. Вы можете узнать про PHIVE на сайте.
Просто добавьте (для разработки) зависимость phpunit/phpunit в файл composer.json вашего проекта, если вы используете Composer для управления зависимостями в вашем проекте:
Обратите внимание, что не рекомендуется устанавливать PHPUnit глобально, например, в /usr/bin/phpunit или /usr/local/bin/phpunit .
Вместо этого PHPUnit должен использоваться в виде локальной зависимости проекта.
Install PHPUNIT with Composer
I have project on Symfony 2 and i would like use PHPUNIT on Windows 7.
First i use system-wide installation but i dont know when this installed. Next i add to my composer.json require-dev. This installed phpunit in C:/wamp/www/myproject/vendor/symfony. Next i try commands:
And i can’t use phpunit. In cmd.exe i enter «phpunit» and i have error:
How can i use phpunit? I have Windows 7, Wamp server and php 5.4.12.
7 Answers 7
When you install PHP-Unit in windows via composer, the global installation will create files in
To execute phpunit easily via command line you need to add path of phpunit.bat file in windows Environment Variables. For this:
- Right click My Computer
- Go to Properties -> Advance system settings and
- Click Environment variables from the Advance tab.
Now add C:\Users\YOUR_USERNAME\AppData\Roaming\Composer\vendor\bin to the windows PATH .
You can now run the phpunit from command. Note that you may need to restart your command prompt for the changes to take effect.