【问题标题】:How can I get my JUnit tests to compile and run in my Kotlin+Gradle project?如何让我的 JUnit 测试在我的 Kotlin+Gradle 项目中编译和运行?
【发布时间】:2016-11-03 01:05:56
【问题描述】:

我根据this previous question 创建了一个 Kotlin+Gradle 项目。我添加了两个源文件:

src/HelloWorld.kt

package com.example.hello

fun main(args : Array<String>) { 
  println("Hello, world!") 
}

测试/HelloWorldTest.kt

package com.example.hello

import org.junit.Assert
import org.junit.Test

class HelloWorldTest {
    @Test
    fun testPasses() {
        Assert.assertTrue(true)
    }

    @Test
    fun testFails() {
        Assert.assertTrue(false)
    }
}

我还将目录src/ 标记为源根目录,并将test/ 标记为测试源根目录。

如果我在别处创建与这些源文件完全相同的目录结构并围绕它创建一个非 Gradle IntelliJ 项目,我就能够编译和运行此代码,包括测试。

但是,在我的 Gradle 版本的项目中,我无法从 IntelliJ IDEA 构建测试。我收到以下错误:

Error:(3, 12) Kotlin: Unresolved reference: junit
Error:(4, 12) Kotlin: Unresolved reference: junit
Error:(7, 6) Kotlin: Unresolved reference: Test
Error:(9, 9) Kotlin: Unresolved reference: Assert
Error:(12, 6) Kotlin: Unresolved reference: Test
Error:(14, 9) Kotlin: Unresolved reference: Assert

奇怪的是,如果我在构建包装器后运行 gradle test(或 ./gradlew test),构建成功且没有错误,但测试没有运行。

  1. 如何以 IntelliJ IDEA 可以看到的方式添加 JUnit?
  2. 如何让 Gradle 真正运行测试?
  3. 为什么 IntelliJ IDEA 和 Gradle 的行为不同,我如何确保它们在我以后构建或运行测试时具有相同的行为?

【问题讨论】:

    标签: intellij-idea gradle junit kotlin


    【解决方案1】:

    您需要将 JUnit 作为依赖项添加到您的 build.gradle(根范围):

    dependencies {
        //... 
        testCompile "junit:junit:4.12"
    }
    

    Junit 5 稍微复杂一点,需要configuring the JUnit Gradle plugin in build.gradle

    1. 由于 IntelliJ IDEA 会解释您的 Gradle 项目并将其内部项目表示与 Gradle 项目同步,因此刷新后它将在测试类路径中看到 JUnit。

    2. 如果您运行 test 任务,Gradle 将运行测试,方法是在终端或 IntelliJ IDEA 中运行 gradlew testGradle 项目(右侧面板)任务验证测试

    3. 如 #1 所述,IntelliJ IDEA 有自己的项目表示,它实际上可能与从 Gradle 项目中导入的内容不同(例如,如果您手动标记为与 Gradle 项目布局定义的源目录不同的源目录)。

      您可以通过运行 刷新所有 Gradle 项目 操作(可在 Gradle 项目 面板中找到)使 IntelliJ IDEA 与您的 build.gradle 同步其项目结构,或者在设置中为您的 Gradle 项目启用使用自动导入

    【讨论】:

    • 供将来参考:“Gradle 项目”面板可以通过从菜单中选择 View → Tool Windows → Gradle 来显示。
    • 谢谢!另一个缺失的难题是我没有在正确的地方找到我的资源。默认情况下,Gradle 显然希望它们位于 src/main/kotlinsrc/test/kotlin 下。
    • 仅供参考,IntelliJ IDEA 有一个捷径 Ctrl+Shift+A "Navigating to Action"。这就是@hotkey 在提到Refresh all Gradle projects 操作时的意思
    • Junit5 的链接已损坏。另外,我们如何在最新版本的 IntelliJ IDEA 中Refresh all Gradle projects
    猜你喜欢
    • 2021-03-15
    • 2016-11-12
    • 2018-08-14
    • 2016-06-14
    • 1970-01-01
    • 2018-06-06
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多