Surefire не собирает тесты Junit 5



я написал простой метод тестирования с JUnit 5:



public class SimlpeTest {
@Test
@DisplayName("Some description")
void methodName() {
// Testing logic for subject under test
}
}


но когда я запускаю mvn test, Я:



-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running SimlpeTest
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0


каким-то образом, surefire не узнал этот тестовый класс. Мой pom.xml выглядит так:



<properties>
<java.version>1.8</java.version>
<junit.version>5.0.0-SNAPSHOT</junit.version>
</properties>

<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<repositories>
<repository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<updatePolicy>always</updatePolicy>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>


есть идеи, как сделать эту работу?

803   8  

8 ответов:

The maven-surefire-plugin сегодня же не имеют полной поддержки JUnit 5. Существует открытый вопрос о добавлении этой поддержки в верный огонь-1206.

таким образом, вы должны использовать поставщик. Один из них уже был разработан командой JUnit; от руководство пользователя, вам необходимо добавить junit-platform-surefire-provider - провайдера и TestEngine реализация для нового API:

<build>
  <plugins>        
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <!-- latest version (2.20.1) does not work well with JUnit5 -->
      <version>2.19.1</version>
      <dependencies>
        <dependency>
          <groupId>org.junit.platform</groupId>
          <artifactId>junit-platform-surefire-provider</artifactId>
          <version>1.0.3</version>
        </dependency>
        <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter-engine</artifactId>
          <version>5.0.3</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>

кроме того, не забудьте объявить junit-jupiter-api зависимость с областью действия test:

<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.0.3</version>
    <scope>test</scope>
  </dependency>
</dependencies>

обновление 2

вопрос была исправлена в maven Surefire плагин v2.22. 0

новая версия доступно в Центральном репозитории Maven.

Maven

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
</dependency>

ш

compile group: 'org.apache.maven.plugins', name: 'maven-surefire-plugin', version: '2.22.0'

обновление

как Марьяна указал, последняя версия Поставщик Surefire Платформы JUnit 5 (1.2.0) поддерживает последнюю версию Плагин Maven Surefire (2.21.0):

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.21.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.2.0</version>
                </dependency>
            </dependencies>
        </plugin>



пример

пом.xml

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.2.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.21.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.2.0</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

TestScenario.java

package test;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

public class TestScenario {

    @Test
    @DisplayName("Test 2 + 2 = 4")
    public void test() {
        Assertions.assertEquals(4, 2 + 2);
    }
}

выход (mvn clean install)

...
[Информация] --- maven-surefire-плагин: 2.21.0: тест (по умолчанию-тест) @ test --- [Информация]
[информация] -------------------------------------------------------
[INFO] T E S T S
[информация] -------------------------------------------------------
[INFO] запуск теста.TestScenario
[INFO] запуск тестов: 1, отказы: 0, Ошибками: 0, пропущено: 0, Время: 0.005 s - в тесте.TestScenario
[INFO]
[INFO] результаты:
[INFO]
[INFO]тесты: 1, Сбои: 0, Ошибки: 0, Пропущено: 0
...


самый простой способ до сегодняшнего дня:

    <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19.1</version>
        <dependencies>
            <dependency>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-surefire-provider</artifactId>
                <version>1.1.0</version>
            </dependency>
        </dependencies>
    </plugin>

я столкнулся с этой проблемой с JUnit5 и Maven, но также заметил, что, даже если только junit-jupiter-engine был добавлен в качестве зависимости,тесты будут выполняться на некоторых проектах, а не на других. И я как бы вижу тот же шаблон в комментариях здесь: в комментарии @Alex выше вы можете видеть, что у него нет никаких проблем, даже с более ранними версиями surefire/junit/platform.

почесав голову в течение некоторого времени я понял, что те проекты, где тесты не побежали бы те, где тесты метод имена ДИТ не содержат слово "тест". Хотя это не предусмотрено http://maven.apache.org/surefire/maven-surefire-plugin/examples/inclusion-exclusion.html

другими словами: только с

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.2.0</version>
        <scope>test</scope>
    </dependency>

этой

@Test
public void something() {
    assertTrue(true);
}

не будет работать, в то время как

@Test
public void testSomething() {
    assertTrue(true);
}

будет работать !

этот вопрос разворачивается в России кукла...

В любом случае, +1 для @Михаила Холодкова, чей обновленный ответ исправляет все проблемы сразу!

У меня была аналогичная проблема, также заставляющая Surefire распознавать нулевые тесты.

моя проблема оказалась связанной со следующим (от JUnit 5.1.0 / maven документация):

из-за утечки памяти в Surefire 2.20 и проблем, запущенных на Java 9, JUnit-platform-surefire-provider в настоящее время работает только с Surefire 2.19.1.

Я пытался использовать последние версии Surefire (2.21.0) и junit-platform-surefire-provider (1.1.0), и он не работал (ни в Java 8, ни в 9)

переключение обратно в Surefire 2.19.1 решило мою проблему.

по данным этот вопрос исправление будет включено в версию 1.2.0 junit-platform-surefire-provider (в настоящее время доступно только как снимок).

С JUnit 5 документация:

начиная с версии 2.22.0, maven Surefire обеспечивает встроенную поддержку для выполнения тестов на платформе JUnit.

кроме того, вы можете прочитать в maven-surefire-plugin документация:

Использование Платформы JUnit 5

чтобы начать работу с платформой JUnit, вам нужно добавить хотя бы один TestEngine реализации ваш проект. Например, если вы хотите напишите тесты с Юпитером, добавьте тестовый артефакт junit-jupiter-engine к зависимостям в POM

так что просто этого достаточно, чтобы выполнить тесты JUnit 5:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>davidxxx</groupId>
    <artifactId>minimal-pom-junit5</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <junit-jupiter.version>5.2.0</junit-jupiter.version> 
        <!--optional below but good practice to specify our java version-->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit-jupiter.version}</version>
            <scope>test</scope>
        </dependency>

        <!--optional below -->
        <!-- add any JUnit extension you need such as -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>${junit-jupiter.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.0</version>
            </plugin>
        </plugins>
    </build>

</project>

в моем пространстве GitHub я добавил рабочий образец проекта maven, который вы можете просматривать/клонировать.
URL: https://github.com/ebundy/junit5-minimal-maven-project

обновление maven-surefire-plugin:2.20 запускает тесты Junit5 без проблем.

но я использую M6 версия на Junit5.

существует открытый вопрос для surefire 2.20

Он работает для меня с surfire 2.19 + junit-platform - * 1.0.3

просто в дополнение, surefire 2.22.0 + junit 5.2.0 + платформа 1.2.0 также работает. Прилагается рабочий pom для вашего referecne:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.jjhome.junit5</groupId>
    <artifactId>junit5-hone</artifactId>
    <packaging>jar</packaging>
    <version>1.0.0-SNAPSHOT</version>
    <name>junit5-home</name>

    <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit5.version>5.2.0</junit5.version>
        <platform.version>1.2.0</platform.version>
        <surefire.version>2.22.0</surefire.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit5.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>${junit5.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit5.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <version>${junit5.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <version>${platform.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-runner</artifactId>
            <version>${platform.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${surefire.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>${platform.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>${junit5.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

Comments

    Ничего не найдено.