首页 > 解决方案 > Eclipse 在错误的目录中创建 JUnit 测试

问题描述

我在 Eclipse 中有一个基于 Gradle 的项目,我想使用 JUnit 5 进行测试。它现在没有任何测试,所以我想添加一个虚拟项目(例如,assertEquals(true, true))以确保 Gradle 可以运行测试。

但是,我遇到两个问题:

1)当我想将 JUnit 测试用例创建为“项目右键单击 --> 新建 --> JUnit 测试用例”时,它会在/src目录内创建一个测试用例。见下图:

在此处输入图像描述

2)当我尝试构建我的 Gradle 配置时,我得到以下输出:

> Task :compileJava FAILED
/home/.../src/main/java/TestFoo.java:1: error: package org.junit does not exist
import static org.junit.Assert.*;
                       ^

据我了解,测试用例无法解析 package org.junit。同时,Eclipse 不允许我在适当的/test目录中创建适当的 JUnit 测试用例。

您认为这里可能的解决方案是什么?我试图找到一种方法来覆盖默认测试目录,但找不到任何方法来做到这一点。

PS 这不是重复的,因为我尝试了这个并且我声明了所有依赖项。以下片段是build.gradle内容(我很抱歉,但由于保密原因,我无法显示其所有内容):


...

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {

    ...

    testCompile group: 'junit', name: 'junit', version: '4.12'
    // Reference: https://www.baeldung.com/junit-5-gradle
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
}

run {
    ...
}

test {
    useJUnitPlatform {
        includeTags 'fast'
        excludeTags 'slow'
    }
}

shadowJar {
    mergeServiceFiles()
    manifest {
        attributes 'Implementation-Title': rootProject.name
        attributes 'Implementation-Version': rootProject.version
        attributes 'Implementation-Vendor-Id': rootProject.group
        attributes 'Created-By': 'Gradle ' + gradle.gradleVersion
        attributes 'Main-Class': mainClassName
    }
    archiveName rootProject.name + '-' + rootProject.version + '.jar'
}

标签: javaeclipsegradlejunit

解决方案


您可以使用这个:如何在 Eclipse 中轻松创建单元测试(回答最多投票)

或安装此插件:httpsCtrl ://moreunit.github.io/MoreUnit-Eclipse/(并使用+创建测试J


推荐阅读