Steven Jeuris
Steven Jeuris

Reputation: 19100

JUnit test in nested Kotlin class not found when running gradle test

When I specify a test in a nested class in Kotlin as follows ...

import org.junit.jupiter.api.*

class ParentTest
{
    @Nested
    class NestedTest
    {
        @Test
        fun NotFoundTest() {}
    }

    @Test
    fun FoundTest() {}
}

... it is not recognized by JUnit when running tests using gradle. Only FoundTest is found and ran.

I am using JUnit 5.1 and Kotlin 1.2.30 and Gradle 4.6.

Upvotes: 27

Views: 10510

Answers (2)

Steven Jeuris
Steven Jeuris

Reputation: 19100

Defining the nested class as an inner class resolves this issue.

class ParentTest
{
    @Nested
    inner class NestedTest
    {
        @Test
        fun InnerTestFound() {}
    }

    @Test
    fun FoundTest() {}
}

As Sam Brannen indicates, "by default, a nested class in Kotlin is similar to a static class in Java" and the JUnit documentation indicates:

Only non-static nested classes (i.e. inner classes) can serve as @Nested test classes.

Marking the class as inner in Kotlin compiles to a non-static Java class.

Upvotes: 42

Marc Philipp
Marc Philipp

Reputation: 1908

From the documentation:

Only non-static nested classes (i.e. inner classes) can serve as @Nested test classes.

Thus, you need to make NestedTest an inner class.

Upvotes: 7

Related Questions