Как протестировать методы в java проекте с использованием фреймворка maven junit5 в eclipse - PullRequest
0 голосов
/ 07 марта 2020

Я создал новый рамочный проект maven junit5 для тестирования существующих java проектов. Я добавил проект java в путь сборки недавно созданного фреймворка maven junit5. Я щелкнул правой кнопкой мыши по методу, для которого я хотел добавить тестовый пример junit, и выбрал новый тестовый случай junit, изменил исходную папку на новый каталог sven c проекта maven junit5 framework и оставил остальные параметры по умолчанию. Создал тест junit и без проблем запустил его как юнит-тест (скриншот ниже). Выполнение того же теста с использованием maven выдает ошибку ниже. Я добавил плагин surefire в pom (ниже), но все равно получаю ошибку ниже. Использование eclipse.

-------------------------------------------------------------------------------
   Test set: com.build.VersionInfoTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 s <<< FAILURE! - in com.build.VersionInfoTest
com.build.VersionInfoTest  Time elapsed: 0.002 s  <<< ERROR!
java.lang.NoClassDefFoundError: Lcom/build/VersionInfo;
Caused by: java.lang.ClassNotFoundException: com.build.VersionInfo

<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>UnitTesting</groupId>
<artifactId>com.unit.testing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>com.unit.testing</name>
<description>Junit Tests</description>
<packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <junit.jupiter.version>5.5.2</junit.jupiter.version>
    <junit.platform.version>1.5.2</junit.platform.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
        </plugin>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
    </plugins>
</build>
</project>

run as junit passes

Обновление: Я очистил пом (ниже), но теперь тесты не обнаружены? когда я запускаю проект с junit, тест обнаружен?

  [INFO] Scanning for projects...
  [INFO] 
  [INFO] --------------< UnitTesting:com.unit.testing >---------------
  [INFO] Building com.unit.testing 1.0-SNAPSHOT
  [INFO] --------------------------------[ jar ]----------------------       -----------
  [INFO] 
  [INFO] --- maven-resources-plugin:2.6:resources (default-resources)      @ com.unit.testing ---
  [INFO] Using 'UTF-8' encoding to copy filtered resources.
  [INFO] Copying 0 resource
  [INFO] 
  [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @     com.unit.testing ---
  [INFO] Nothing to compile - all classes are up to date
  [INFO] 
  [INFO] --- maven-resources-plugin:2.6:testResources (default-    testResources) @ com.unit.testing ---
  [INFO] Using 'UTF-8' encoding to copy filtered resources.
  [INFO] Copying 0 resource
  [INFO] 
  [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ com.unit.testing ---
  [INFO] Nothing to compile - all classes are up to date
  [INFO] 
  [INFO] --- maven-surefire-plugin:3.0.0-M4:test (default-test) @   com.unit.testing ---
  [INFO] 
  [INFO] -------------------------------------------------------
  [INFO]  T E S T S
  [INFO] -------------------------------------------------------
  [INFO] Running com.build.VersionInfoTest
  [INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time   elapsed: 0.002 s - in com.build.VersionInfoTest
  [INFO] 
  [INFO] Results:
  [INFO] 
  [INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
  [INFO] 
  [INFO] ------------------------------------------------------------------------
  [INFO] BUILD SUCCESS
  [INFO] ------------------------------------------------------------------------
  [INFO] Total time: 1.955 s
  [INFO] Finished at: 2020-03-09T10:00:22-04:00
  [INFO] ------------------------------------------------------------------------


    <packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>${maven.compiler.source}</maven.compiler.target>
    <junit.jupiter.version>5.6.0</junit.jupiter.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>${junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
             <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
        </plugin>
    </plugins>
</build>

  package com.dbb.build

  import static org.junit.jupiter.api.Assertions.*;
  import org.junit.jupiter.api.Test;
  import com.dbb.build.VersionInfo;

  class VersionInfoTest {

VersionInfo versionInfo = VersionInfo.getInstance();

@Test
void getVersion() {
    String version = versionInfo.getVersion();
    System.out.println(version);
    assertNotNull(versionInfo.getVersion(), "expected a return value of"+version+"but was null");
}
  }

ОБНОВЛЕНИЕ:

  [INFO] --- maven-resources-plugin:2.6:testResources (default- testResources) @ DBB-Unit-Testing ---
  [INFO] Using 'UTF-8' encoding to copy filtered resources.
  [INFO] Copying 0 resource
  [INFO] 
  [INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ DBB-Unit-Testing ---
  [INFO] Changes detected - recompiling the module!
  [INFO] Compiling 1 source file to /Unit-Testing/target/test-classes
  [INFO] -------------------------------------------------------------
  [ERROR] COMPILATION ERROR : 
  [INFO] -------------------------------------------------------------
  [ERROR] /Unit-Testing/src/test/java/com/VersionInfoTest.java:[7,25]  cannot find symbol
   symbol:   class VersionInfo
   location: package com.build
  [ERROR] /Unit-Testing/src/test/java/com/build/VersionInfoTest.java: [11,9] cannot find symbol
  symbol:   class VersionInfo
  location: class com.build.TestVersionInfo
 [ERROR] /Unit-Testing/src/test/java/com/ /build/VersionInfoTest.java:  [11,35] cannot find symbol
   symbol:   variable VersionInfo
   location: class com.build.TestVersionInfo
   [INFO] 3 errors

Решение: Использование junit-platform-console-standalone-1.5.2.jar и запуск модулей с помощью команды линия. Похоже, если у нас есть не maven проект, то junit-platform-console-standalone кажется лучшим вариантом.

1 Ответ

1 голос
/ 07 марта 2020

Вот пример некоторых моих pom, которые я использую с Maven 3.x и тесты, выполненные, как и ожидалось, с JUnit 5 в Eclipse, но также и из командной строки:

Не добавляйте слишком много артефактов Juniper, некоторые из них создадут некоторый побочный эффект, если он присутствует.

Обратите внимание, что обновленная версия плагина surefire с некоторыми проблемами в прошлом была связана с JUnit5

    <properties>
        <!-- ensure proper encoding of source and resource files in the project -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <junit-5.version>5.6.0</junit-5.version>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
            </plugin>
        </plugins>
    </build>


ОБНОВЛЕНИЕ:

Вы можете найти небольшой пример здесь: https://gist.github.com/asa-git/8e34bbc51b5fcb09b7fab3efdaaa73c9

Обратите внимание, что я использую Maven версии 3.6.3 и JDK 8.

Кроме того, при запуске из в командной строке windows (но также и в других системах) вы должны убедиться, что ваш JDK находится на вашем пути, прежде чем любой другой JSE установленный в вашей системе.

...