Как подключить testng к idea

Кратко о том, как легко подключить JUnit в IntelliJ IDEA

Дата публикации: 2019-01-24

От автора: установить и настроить IntelliJ IDEA — это только малая часть задачи, которую нужно совершить перед тем, как ваша работа станет полноценной. Поэтому продолжаем рассматривать некоторые важные функции, которые не включены в среду разработки по умолчанию. К примеру, многие начинающие пользователи не знают, как подключить JUnit в IntelliJ IDEA. Эту и другие трудности вы сможете преодолеть, руководствуясь коротким мануалом, который представим в сегодняшней статье.

Тесты — панацея

Конечно, нет. Но отказываться от модульного тестирования глупо. Оно позволяет проверить, насколько правильными являются элементы исходного кода. А вместе с «умной» IntelliJ IDEA этот функционал становится еще более полезным, так как система предлагает нужные исправления. При этом типе тестирования изолируем фрагмент программы и смотрим, насколько хорошо он справляется с возложенными на него задачами. Если что-то пошло не так — исправляем. Благодаря такому подходу программист знает, что «ложь» не из-за всей программы, а вызвана конкретным ее элементом.

Одной из наиболее распространённых библиотек модульного тестирования является JUnit. Она разработана специально для Java, но из-за ее крутизны была портирована на массу других языков: начиная с веб-языка PHP, заканчивая такими динозаврами, как Fortran. Из-за того, что выполнение происходит через Java Virtual Machine, инструмент является полностью кроссплатформенным, а потому популярным.

Подключить к IDEA

Это наша главная задача сегодня. Будем показывать, как происходит взаимодействие этой технологии и одной из самых популярных сред разработки — IntelliJ IDEA. Заодно по пути продемонстрируем подключение еще одной тестовой технологии — TestNG, так как они, как правило, используются в паре.

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Библиотеки для JUnit и TestNG поставляются с IntelliJ IDEA, но по умолчанию не включены в путь к классам вашего проекта или модуля. Следовательно, при создании тестового класса ссылки на класс TestCase или текстовые аннотации не разрешаются.

Чтобы добавить необходимую библиотеку в путь к классам, вы можете использовать общую процедуру добавления зависимости к модулю. Соответствующие библиотеки расположены в следующих каталогах:

JUnit библиотеки ( junit.jar и junit-4.12.jar): \lib;

библиотека TestNG (testng-jdk15.jar): \plugins\testng\lib.

IntelliJ IDEA может автоматически добавить необходимую библиотеку в путь к классам. Соответствующие функции доступны при создании теста для класса или при написании кода для теста.

Теперь добавим библиотеку тестов в путь к классам при создании теста для класса.

В редакторе поместите курсор в строку, содержащую объявление класса.

Нажмите Alt+Enter, чтобы просмотреть доступные намеренные действия.

Выберите «Создать тест».

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

В диалоговом окне «Создать тест», справа от текста, сообщающего, что соответствующая библиотека не найдена, нажмите «Исправить».

А после добавим библиотеку тестов в classpath при написании кода для теста.

В исходном коде тестового класса поместите курсор в неразрешенную ссылку TestCase или аннотацию.

Нажмите Alt+Enter, чтобы просмотреть доступные намеренные действия.

Вот и все, сконфигурированы библиотеки для тестирования, и можем переходить к некоторым другим полезным возможностям, которые может подарить нам настройка IntelliJ IDEA.

Расширение для Android Developers

Теперь перейдем к инструментам для мобильных разработчиков. Дело в том, что IntelliJ IDEA c установленным Android SDK может конкурировать со средами разработки, которые созданы специально для того, чтобы делать приложения для мобильной операционной системы. Потому расскажем о том, как прокачать вашу IDE до профессионального инструмента для Android.

Для начала, необходимо скачать Android SDK с официального сайта, и это важно. Не стоит искать другие источники, когда программное обеспечение распространяется свободно. Кстати, имеется в виду установка на 64-разрядную операционную систему. Если у вас 32-разрядная, то для начала займитесь своим ПК, а после приступайте к работе с IntelliJ IDEA.

Итак, стянули Android SDK c сети, и теперь пора его установить. При скачивании выбираем пункт «…для существующей IDE». Если ранее вы работали с Java продуктами, то следующий шаг покажется знакомым: установщик не видит Java SDK. Для того, чтобы все исправить, переходим в переменные среды и вносим необходимые изменения. Создаем значение переменной «JAVA_HOME», а в значении указываем, где вы установили Java.

Теперь открываем установщик заново и ставим пакеты. Среди нужных:

установить Android SDK Tools;

версии ОС, для которых будем создавать приложения;

версия минимальной совместимости.

Далее жмем кнопку установки и просто ждем несколько минут. Соглашаемся со всеми условиями и идем дальше. Затем настраиваем все для вашей IDE: показываем, какую среду будем использовать и где расположена Java SDK. А непосредственно в IDE указываем путь к набору Android. Готово!

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Редактор Sublime Text

Посмотрите видео по работе с редактором Sublime Text

Источник

Run/Debug Configuration: TestNG

The TestNG run/debug configuration is used to launch the tests that comply with the TestNG framework. The dialog consists of the following tabs:

Configuration tab

All in package – run all tests in a package. In the Package field, specify the fully qualified name of the package.

Pattern – run the tests that conform to the specified pattern. In the Pattern field, enter one or more TestNG test classes.

Group – run a test group. In the Group field, specify the group you want to run.

Suite – run a test suite. In the Suite field, enter the corresponding testng.xml file.

In whole project – the IDE will look for the tests in all the modules

Читайте также:  Шорт лист номинации что это

In single module – the IDE will look for the tests only in the module that is selected in the Use classpath of module field.

Across module dependencies – the same as the previous option plus the modules that depend on that module.

Class – run a test class. In the Class field, enter the fully qualified name of the test class you want to run.

Method – run a test method.

The directory in which test reports will be generated.

Options and arguments to be passed to the JVM in which the tests run.

When specifying JVM options, follow these rules:

Test runner parameters

Arguments to be passed to the test runner.

Use the same rules as for specifying the VM options.

The current working directory for the tests.

The environment variables to be passed to the corresponding JVM.

Use classpath of module

The module whose classpath is used when running the tests.

This checkbox is available for projects with JPMS modules (Java 9 and later). It allows you to select how to run your tests: on a class or on a module path.

The JRE to be used.

Shorten command line

none : IntelliJ IDEA will not shorten a long classpath. If the command line exceeds the OS limitation, IntelliJ IDEA will be unable to run your application and will display a message suggesting you to specify the shortening method.

classpath.file : IntelliJ IDEA will write a long classpath into a text file.

@argFiles (java 9+) : the command-line length limitations will be overcome using the @argument files option.

Use these icons to make up a list of listeners.

Code Coverage tab

Use this tab to configure code coverage monitoring options.

Choose coverage runner

Select the desired code coverage runner.

By default, IntelliJ IDEA uses its own coverage engine with the Sampling mode. You can also choose JaCoCo or Emma for calculating coverage.

Select this option to measure code coverage with minimal slow-down.

Select this option to collect accurate branch coverage. This mode is available for the IntelliJ IDEA code coverage runner only.

Track per test coverage

Select this checkbox to detect lines covered by one test and all tests covering line. If this checkbox is selected, becomes available on the toolbar of the coverage statistic popup.

This option is only available for the Tracing mode of code coverage measurement for the testing run/debug configurations.

Packages and classes to record code coverage data

Enable coverage in test folders.

If this checkbox is selected, the folders marked as test are included in the code coverage analysis.

Logs tab

Use this tab to specify which log files generated while running or debugging should be displayed in the console, that is, on the dedicated tabs of the Run or Debug tool window.

Select checkboxes in this column to have the log entries displayed in the corresponding tabs in the Run tool window or Debug tool window.

The read-only fields in this column list the log files to show. The list can contain:

Full paths to specific files.

Ant patterns that define the range of files to be displayed.

Aliases to substitute for full paths or patterns. These aliases are also displayed in the headers of the tabs where the corresponding log files are shown.

If a log entry pattern defines more than one file, the tab header shows the name of the file instead of the log entry alias.

Select this checkbox to have the previous content of the selected log skipped.

Save console output to file

Show console when a message is printed to standard output stream

Select this checkbox to activate the output console and bring it forward if an associated process writes to Standard.out.

Show console when a message is printed to standard error stream

Select this checkbox to activate the output console and bring it forward if an associated process writes to Standard.err.

Click this button to open the Edit Log Files Aliases dialog where you can select a new log entry and specify an alias for it.

Click this button to edit the properties of the selected log file entry in the Edit Log Files Aliases dialog.

Click this button to remove the selected log entry from the list.

Common settings

When you edit a run configuration (but not a run configuration template), you can specify the following options:

Allow parallel run

Select to allow running multiple instances of this run configuration in parallel.

By default, it is disabled, and when you start this configuration while another instance is still running, IntelliJ IDEA suggests to stop the running instance and start another one. This is helpful when a run/debug configuration consumes a lot of resources and there is no good reason to run multiple instances.

Store as project file

Toolbar

The tree view of run/debug configurations has a toolbar that helps you manage configurations available in your project as well as adjust default configurations templates.

Create a run/debug configuration.

Delete the selected run/debug configuration. Note that you cannot delete default configurations.

Create a copy of the selected run/debug configuration. Note that you create copies of default configurations.

The button is displayed only when you select a temporary configuration. Click this button to save a temporary configuration as permanent.

Читайте также:  Кто такой масленок человек

Move into new folder / Create new folder. You can group run/debug configurations by placing them into folders.

Click this button to sort configurations in the alphabetical order.

Before launch

In this area, you can specify tasks to be performed before starting the selected run/debug configuration. The tasks are performed in the order they appear in the list.

Click this icon to add one of the following available tasks:

Run External tool : select to run an external application. In the dialog that opens, select one or multiple applications you want to run. If it is not defined in IntelliJ IDEA yet, add its definition. For more information, see External tools and External Tools.

Run Another Configuration : select to execute another run/debug configuration. In the dialog that opens, select the configuration to be run.

Build : select to compile the specified module. The Build Module command will be executed.

If an error occurs during compilation, IntelliJ IDEA won’t attempt to start the run/debug configuration.

Build Project : select to compile the entire project. The Build Project command will be executed.

If an error occurs during compilation, IntelliJ IDEA won’t attempt to start the run/debug configuration.

Build, no error check : the same as the Build option, but IntelliJ IDEA will try to start the run/debug configuration irrespective of the compilation results.

Build Artifacts : select this option to build an artifact or artifacts. In the dialog that opens, select the artifact or artifacts that should be built.

Launch Web Browser : select this option to have a browser started. In the dialog that opens, select the type of the browser and provide the start URL. Also, specify if you want the browser be launched with JavaScript debugger.

Run Ant target : select this option to run an Ant target. In the dialog that opens, select the target to be run.

Run Grunt task : select this option to run a Grunt task.

In the Grunt task dialog that opens, specify the Gruntfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Grunt tool.

Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the grunt-cli package.

Run gulp task : select this option to run a Gulp task.

In the Gulp task dialog that opens, specify the Gulpfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Gulp tool.

Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the gulp package.

Run Maven Goal : select this option to run a Maven goal. In the dialog that opens, select the goal to be run.

Run npm script : select this option to execute an npm script.

In the NPM Script dialog that opens, specify the npm run/debug configuration settings.

Compile TypeScript : select to run the built-in TypeScript compiler and thus make sure that all the changes you made to your TypeScript code are reflected in the generated JavaScript files. In the TypeScript Compile Settings dialog that opens, select or clear the Check errors checkbox to configure the behaviour of the compiler in case any errors are detected:

If the Check errors checkbox is selected, the compiler will show all the errors and the run configuration will not start.

If the Check errors checkbox is cleared, the compiler will show all the detected errors but the run configuration still will be launched.

Generate CoffeeScript Source Maps : select this option to generate the source maps for your CoffeeScript sources. In the dialog that opens, specify where your CoffeeScript source files are located.

Run Remote External Tool : adds a remote SSH external tool.

Note that code completion is available here.

Run JRuby compiler : choose this option to execute JRuby compiler with the specified target path, compiler process heap size, and command line parameters (if any).

Click this icon to remove the selected task from the list.

Click this icon to edit the selected task. Make the necessary changes in the dialog that opens.

Click these icons to move the selected task one line up or down in the list. The tasks are performed in the order that they appear in the list.

Select this checkbox to show the run/debug configuration settings prior to actually starting the run/debug configuration.

Activate tool window

By default this checkbox is selected and the Run or the Debug tool window opens when you start the run/debug configuration.

This setting is shared if you select to share your run/debug configuration, so the same method will be applied for your team members irrespective of their operating system.

Источник

Sharing is Caring

If you are new to TestNG or Intellij IDEA, first day unit testing with TestNG won’t be easy. So Lets check How to start unit Testing with TestNG in Intellij. Here I’m going to Show it using maven web app template (For my ease.) First lets create the maven web app. run below command for it.

Читайте также:  Как подключить вай фай аэрофлот

Now my web app is created. Lets open it in Intellij (Open or Import just prompt where the pom.xml is then next …)

For the ease of understanding I use to follow below project structuring in my projects.

If you create folder structure like mine, Now we have to indicate which folder is which.

Sources – src/main/java

test source – src/test/java

test resources – src/test/resources

There is two way of declaring directories. First one is using Project Structure dialog box. To open it use

Select Modules Now you can see below window.

The Other way of doing this right click on the folder you want and Mark Directory as.. But I recommend First way it’s more visual.

Lets create a simple java class (which return the String after concatenating ) to test in package hsenid (in src/main/java).

Now you have a class lets write a simple test class. Easiest way is to go class name line (public class MyConcatenator) the press Alt + Enter then Create Test

you will get below window.

Select TestNG as testing library. If you are using testng first time in the Intellij you will get TestNG library not found in the module warning. Don’t worry, just click Fix button on right upper corner. Since We want to create for Method concatenate select it from Member area. ( If you can’t see TestNG library as a Selection Follow below link to fix it. http://stackoverflow.com/questions/19438414/how-to-add-testing-library-e-g-junit-to-intellij-create-test-class-dialog/36276429#36276429).

Now you can see you Test class in hsenid package in src/test/java. Add below code to your Test class.

When Creating testng.xml you must add

This doctype declare to Intellij that we are creating a testng.xml. So it can suggest us the relevant tags for Testng.xml

Then you can see a out put like below.

Источник

Prepare for testing

IntelliJ IDEA works with multiple testing frameworks out of the box, for example, JUnit, TestNG, Cucumber, or Arquillian JUnit.

In the IDE, you can create a test class directly from the source code together with the necessary test methods. You can switch between test classes and source code with a shortcut, run multiple tests, view statistics for each test, and export test results to a file.

IntelliJ IDEA also features code coverage that allows you to analyze your code and understand which areas of your code are covered by tests and which areas require more testing.

Add testing libraries

IntelliJ IDEA allows you to add missing libraries as you code: once the IDE detects that you’re using some code from the library that is not added to your project yet, it will prompt you to download and install it.

You can also add libraries to your project manually. For example, this can be helpful if you need a specific library version or distribution.

Manually add a testing library

Follow these steps to add a library if you’re building your project with the native IntelliJ IDEA builder:

Apply the changes and close the dialog.

You can also add libraries to your project manually. For example, this can be helpful if you need a specific library version or distribution.

Manually add a testing library

Follow these steps if you’re using Maven in your project:

In the dialog that opens, type the necessary artifact. For example, type org.junit.jupiter:junit-jupiter:5.4.2 to add the JUnit library.

For more information on how to work with Maven, refer to Maven dependencies.

In Gradle projects, add the necessary dependencies to your build file manually:

Open your build.gradle and add a dependency to the necessary testing library.

For example, if you want to use JUnit 5, add the unit test platform:

Then, add the dependency to the testing library:

For more information on how to work with Gradle, refer to Gradle projects.

Test Sources Root

The IDE processes the code from different sources differently. For example, compilation results for sources and test sources are normally placed into different folders. That is why, if the test sources root is missing, you need to create one. Otherwise, your code might be processed incorrectly.

Create a test root for your project

Follow these steps if you’re building your project with the native IntelliJ IDEA builder:

However, you can override the standard directory layout by modifying the build file.

Change the test root

Replace src/new-test/test with the path to the folder that you want to use as a test root.

However, you can override the standard directory layout by modifying the build file.

Use another test root

Open your build.gradle and add the following code.

Replace src/new-test/test with the path to the folder that you want to use as a test root.

Add one more test root

Open your build.gradle and add the following code.

Replace src/new-test/test with the path to the folder that you want to use as a test root.

For more information on different types of folders, refer to Folder categories.

Create Test Resources Root

For Maven and Gradle projects, the test resources folder is usually created automatically. If you’re building your project with the native IntelliJ IDEA builder, you might need to create the resource root manually.

Configure the folder for test resources

Источник

Познавательно-развлекательный портал