Maven surefire plugin для чего
Перейти к содержимому

Maven surefire plugin для чего

  • автор:

Maven surefire plugin для чего

Maven Surefire Plugin

  • Apache /
  • Maven /
  • Surefire /
  • Maven Surefire Plugin /
  • Introduction
  • | Last Published: 2023-10-24
  • Version: 3.2.1

Maven Surefire Plugin

Requirements: Maven 3.2.5 and JDK 1.8 or higher.

The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application. It generates reports in two different file formats:

  • Plain text files ( *.txt )
  • XML files ( *.xml )

By default, these files are generated in $/target/surefire-reports/TEST-*.xml .

The schema for the Surefire XML reports is available at Surefire XML Report Schema.

For an HTML format of the report, please see the Maven Surefire Report Plugin.

Goals Overview

The Surefire Plugin has only one goal:

  • surefire:test runs the unit tests of an application.

Usage

General instructions on how to use the Surefire Plugin can be found on the usage page. Some more specific use cases are described in the examples listed below. Additionally, users can contribute to the GitHub project.

In case you still have questions regarding the plugin’s usage, please have a look at the FAQ and feel free to contact the user mailing list. The posts to the mailing list are archived and could already contain the answer to your question as part of an older thread. Hence, it is also worth browsing/searching the mail archive.

If you feel like the plugin is missing a feature or has a defect, you can file a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.

Examples

The following examples show how to use the Surefire Plugin in more advanced use cases:

  • Using TestNG
  • Using JUnit 5 Platform
  • Using JUnit
  • Using POJO Tests
  • Skipping Tests
  • Skip After Failure
  • Inclusions and Exclusions of Tests
  • Running a Single Test
  • Re-run Failing Tests
  • Class Loading and Forking
  • Debugging Tests
  • Using System Properties
  • Configuring the Classpath
  • Selecting Providers
  • Fork Options and Parallel Test Execution
  • Using Console Logs
  • Shutdown of Forked JVM
  • Run tests with Java 9
  • Run tests in Docker

Apache Maven Surefire Plugin, Maven Surefire Plugin, Apache, the Apache feather logo, and the Apache Maven Surefire Plugin project logos are trademarks of The Apache Software Foundation.

Разница между плагинами Maven Surefire и Failsafe

В типичной разработке через тестирование мы стремимся написать много низкоуровневых модульных тестов, которые быстро запускаются и настраиваются изолированно. Кроме того, есть также несколько высокоуровневых интеграционных тестов, которые зависят от внешних систем, например, настройка сервера или баз данных. Неудивительно, что они, как правило, требуют как ресурсов, так и времени.

Следовательно, эти тесты в основном требуют некоторой настройки перед интеграцией и очистки после интеграции для корректного завершения. Поэтому желательно различать два типа тестов и иметь возможность запускать их отдельно в процессе сборки.

В этом руководстве мы сравним подключаемые модули Surefire и Failsafe, наиболее часто используемые для запуска различных типов тестов в типичной сборке Apache Maven .

2. Плагин Surefire​

Плагин Surefire принадлежит к набору основных плагинов Maven и запускает модульные тесты приложения.

POM проекта включает этот плагин по умолчанию, но мы также можем настроить его явно:

 build>   pluginManagement>   plugins>   plugin>   groupId>org.apache.maven.pluginsgroupId>   artifactId>maven-surefire-pluginartifactId>   version>3.0.0-M5version>   .   plugin>   plugins>   pluginManagement>   build> 

Плагин привязывается к тестовой фазе жизненного цикла по умолчанию . Поэтому выполним его командой:

 mvn clean test 

Это запускает все модульные тесты в нашем проекте. Поскольку подключаемый модуль Surefire связывается с фазой тестирования , в случае каких-либо сбоев теста сборка завершается с ошибкой, и в процессе сборки дальнейшие фазы не выполняются .

Кроме того, мы можем изменить конфигурацию плагина для запуска интеграционных тестов, а также модульных тестов. Однако это может быть нежелательным поведением для интеграционных тестов, которые могут потребовать некоторой предварительной настройки среды, а также некоторой очистки после выполнения теста.

Maven предоставляет другой плагин именно для этой цели.

3. Отказоустойчивый плагин​

Плагин Failsafe предназначен для запуска интеграционных тестов в проекте.

3.1. Конфигурация​

Во-первых, давайте настроим это в проекте POM:

 plugin>   artifactId>maven-failsafe-pluginartifactId>   version>3.0.0-M5version>   executions>   execution>   goals>   goal>integration-testgoal>   goal>verifygoal>   goals>   .   execution>   executions>   plugin> 

Здесь цели плагина связаны с интеграционным тестом и проверяют этапы цикла сборки для выполнения интеграционных тестов.

Теперь давайте выполним фазу проверки из командной строки:

 mvn clean verify 

Это запускает все интеграционные тесты, но если какие-либо тесты терпят неудачу на этапе интеграционного тестирования , плагин не сразу завершает сборку .

Вместо этого Maven по-прежнему выполняет фазу тестирования после интеграции . Поэтому мы по-прежнему можем выполнять любую очистку и демонтаж среды в рамках фазы постинтеграционного тестирования . На последующем этапе проверки процесса сборки сообщается обо всех неудачных тестах.

3.2. Пример​

В нашем примере мы настроим сервер Jetty так, чтобы он запускался до запуска интеграционных тестов и останавливался после выполнения теста.

Во-первых, давайте добавим плагин Jetty в наш POM:

 plugin>   groupId>org.eclipse.jettygroupId>   artifactId>jetty-maven-pluginartifactId>   version>9.4.11.v20180605version>   .   executions>   execution>   id>start-jettyid>   phase>pre-integration-testphase>   goals>   goal>startgoal>   goals>   execution>   execution>   id>stop-jettyid>   phase>post-integration-testphase>   goals>   goal>stopgoal>   goals>   execution>   executions>   plugin> 

Здесь мы добавили конфигурацию для запуска и остановки сервера Jetty на этапах до и после тестирования интеграции соответственно.

Теперь давайте еще раз выполним наши интеграционные тесты и посмотрим на вывод консоли:

 ....   [INFO]  jetty-maven-plugin:9.4.11.v20180605:start (start-jetty)    validate @ maven-integration-test    [INFO] --- jetty-maven-plugin:9.4.11.v20180605:start (start-jetty)   @ maven-integration-test ---  [INFO] Started ServerConnector@4b9dc62fHTTP/1.1,[http/1.1]>0.0.0.0:8999>   [INFO] Started @6794ms  [INFO] Started Jetty Server  [INFO]   [INFO] --- maven-failsafe-plugin:3.0.0-M5:integration-test (default)   @ maven-integration-test ---  [INFO]   [INFO] -------------------------------------------------------  [INFO] T E S T S  [INFO] -------------------------------------------------------  [INFO] Running com.foreach.maven.it.FailsafeBuildPhaseIntegrationTest  [ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.024 s   FAILURE! - in com.foreach.maven.it.FailsafeBuildPhaseIntegrationTest  [ERROR] com.foreach.maven.it.FailsafeBuildPhaseIntegrationTest.whenTestExecutes_thenPreAndPostIntegrationBuildPhasesAreExecuted  Time elapsed: 0.012 s  FAILURE!  org.opentest4j.AssertionFailedError: expected: true> but was: false>   at com.foreach.maven.it.FailsafeBuildPhaseIntegrationTest  .whenTestExecutes_thenPreAndPostIntegrationBuildPhasesAreExecuted(FailsafeBuildPhaseIntegrationTest.java:11)   [INFO]   [INFO] Results:  [INFO]   [ERROR] Failures:  [ERROR] FailsafeBuildPhaseIntegrationTest.whenTestExecutes_thenPreAndPostIntegrationBuildPhasesAreExecuted:11  expected: true> but was: false>   [INFO]   [ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0   [INFO]   [INFO] --- jetty-maven-plugin:9.4.11.v20180605:stop (stop-jetty)   @ maven-integration-test ---  [INFO]   [INFO] --- maven-failsafe-plugin:3.0.0-M5:verify (default)   @ maven-integration-test ---  [INFO] Stopped ServerConnector@4b9dc62fHTTP/1.1,[http/1.1]>0.0.0.0:8999>   [INFO] node0 Stopped scavenging  [INFO] ------------------------------------------------------------------------  [INFO] BUILD FAILURE  [INFO] ------------------------------------------------------------------------  .... 

Здесь, согласно нашей конфигурации, сервер Jetty запускается до выполнения интеграционного теста. Для демонстрации у нас есть неудачный интеграционный тест, но это не приводит к немедленному сбою сборки. Фаза тестирования после интеграции выполняется после выполнения теста, и сервер останавливается до сбоя сборки.

Напротив, если бы мы использовали подключаемый модуль Surefire для запуска этих интеграционных тестов, сборка остановилась бы на этапе интеграционного тестирования без выполнения какой-либо необходимой очистки .

Дополнительным преимуществом использования разных плагинов для разных типов тестов является разделение между различными конфигурациями. Это улучшает ремонтопригодность сборки проекта.

4. Вывод​

В этой статье мы сравнили плагины Surefire и Failsafe для разделения и запуска разных типов тестов. Мы также рассмотрели пример и увидели, как Failsafe Plugin предоставляет дополнительные функции для запуска тестов, требующих дополнительной настройки и очистки.

Как всегда, код доступен на GitHub .

What is the use of Maven-Surefire plugin

The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application. It generates reports in two different file formats Plain text files (.txt) XML files (.xml)

answered Oct 5, 2015 at 7:06
Amey Jadiye Amey Jadiye
3,086 3 3 gold badges 25 25 silver badges 39 39 bronze badges

It really astonishes me (also in with other maven plugins) that the description what they actually DO (especially suitable for a maven beginner) is hidden somehwhere in the middle of the page.

Jan 4, 2019 at 17:56

Yeah, they have a commercial tie-up with stackoverflow to actually know the use of it 😉 .. just kidding.

Jan 5, 2019 at 16:08

Even the line quoted here doesn’t tell much. For instance what report does it generate, what is the actual value proposition of this plugin

Feb 21, 2020 at 6:57

Maven sure fire plugin is used to follow the sequence of tests in testng.xml file. If we don’t include the Mavwen surefire plugin then it will execute all the testcases under src/test/java which has prefix or suffix as ‘test’ and these tests will get executed without any sequence.

answered Jul 19, 2018 at 2:42
fakirchand fakirchand
151 1 1 silver badge 8 8 bronze badges

Here you can find best description of what surefire is, and what role does it play in lifecycle of maven.

It is called implicitely by the maven lifecycle in the appropiate phase so it is a ‘special’ plugin. We don´t need to define it inside pom.xml it will be downloaded and executed when maven needs it.

It has only one goal inside it, and undoubtly it is «test», and defined by apache folks,

test: Allow us to run the unit tests of the application

Though, we can denote it inside pom.xml to run our unit tests of src/test/java folder.

   maven-jar-plugin 2.4  org.apache.maven.plugins maven-surefire-plugin 2.19    

Maven surefire plugin для чего

Maven Surefire Plugin

  • Apache /
  • Maven /
  • Surefire /
  • Maven Surefire Plugin /
  • Usage
  • | Last Published: 2023-10-24
  • Version: 3.2.1

Usage

Best practice is to define the version of the Surefire Plugin that you want to use in either your pom.xml or a parent pom.xml :

 [. ]    org.apache.maven.plugins maven-surefire-plugin 3.2.1     [. ] 

The Surefire Plugin can be invoked by calling the test phase of the build lifecycle.

mvn test

Using Different Testing Providers

Tests in your test source directory can be any combination of the following:

  • TestNG
  • JUnit (3.8, 4.x or 5.x)
  • POJO

Which providers are available is controlled simply by the inclusion of the appropriate dependencies (i.e., junit:junit or junit:junit-dep for JUnit4, junit-jupiter-engine or junit-vintage-engine for JUnit5 and org.testng:testng 4.7+ for TestNG). Since this is required to compile the test classes anyway, no additional configuration is required.

Note that any normal Surefire integration works identically no matter which providers are in use — so you can still produce a Cobertura report and a Surefire results report on your project web site for your TestNG tests, for example.

The POJO provider above allows you to write tests that do not depend on either of JUnit and TestNG. It behaves in the same way, running all test* methods that are public in the class, but the API dependency is not required. To perform assertions, the JDK 1.4 assert keyword can be used. See Using POJO Tests for more information.

All of the providers support the Surefire Plugin parameter configurations. However, there are additional options available if you are running TestNG tests (including if you are using TestNG to execute your JUnit tests, which occurs by default if both are present in Surefire).

See Using TestNG for more information.

Apache Maven Surefire Plugin, Maven Surefire Plugin, Apache, the Apache feather logo, and the Apache Maven Surefire Plugin project logos are trademarks of The Apache Software Foundation.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *