Reputation: 143064
I have created a Kotlin+Gradle project as per this previous question. I added two source files to it:
package com.example.hello
fun main(args : Array<String>) {
println("Hello, world!")
}
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.
Upvotes: 7
Views: 6365
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
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.
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) → Tasks → verification → test.
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