Laurence Gonsalves
Laurence Gonsalves

Reputation: 143064

How can I get my JUnit tests to compile and run in my Kotlin+Gradle project?

I have created a Kotlin+Gradle project as per this previous question. I added two source files to it:

src/HelloWorld.kt

package com.example.hello

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

tests/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)
    }
}

I have also marked the directory src/ as a sources root and test/ as a test sources root.

If I create the exact same directory structure with these source files elsewhere and create a non-Gradle IntelliJ project around it I am able to compile and run this code, including the tests.

In my Gradle version of the project, however, I can't build the tests from IntelliJ IDEA. I get the following errors:

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

Strangely, if I run gradle test (or ./gradlew test after building the wrapper) the build succeeds without error, but the tests are not run.

  1. How do I add JUnit in such a way that IntelliJ IDEA can see it?
  2. How to I get Gradle to actually run the tests?
  3. Why are IntelliJ IDEA and Gradle behaving differently, and how can I ensure that they have the same behavior when I build or run tests in the future?

Upvotes: 7

Views: 6365

Answers (1)

hotkey
hotkey

Reputation: 147901

You need to add JUnit as a dependency to your build.gradle (root scope):

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

It's a bit more complicated for Junit 5, it requires configuring the JUnit Gradle plugin in build.gradle

  1. Since IntelliJ IDEA interprets your Gradle project and synchronizes its internal project representation with the Gradle project, after a refresh it will see JUnit in the tests classpath.

  2. Gradle will run the tests if you run the test task, either by running gradlew test in terminal or in IntelliJ IDEA: Gradle projects (panel on the right)Tasksverificationtest.

  3. As said in #1, IntelliJ IDEA has its own project representation, and it may actually differ from what it imports from Gradle project (e.g. if you manually mark as sources directories different from those which Gradle project layout defines).

    You can make IntelliJ IDEA synchronize its project structure with your build.gradle by running Refresh all Gradle projects action (can be found in the Gradle projects panel), or enable Use auto-import for your Gradle project in Settings.

Upvotes: 5

Related Questions