23

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.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161

2 Answers2

35

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.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
6

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.

Marc Philipp
  • 1,848
  • 12
  • 25
  • 1
    I did read that, but be aware this is Java documentation. 'static' is not a thing in Kotlin and the reference to 'inner' class is not exactly the same as the 'inner' keyword for [inner classes in kotlin](https://kotlinlang.org/docs/reference/nested-classes.html). For example, does this mean by default Kotlin classes all compile to static classes? That said, reading this is why I tried specifying the class as (Kotlin) inner orginally, just not certain about the specifics. – Steven Jeuris Mar 09 '18 at 09:06
  • 2
    Yes, by default, a _nested_ class in Kotlin is similar to a `static` class in Java. – Sam Brannen Mar 10 '18 at 16:18
  • Nesting classes in Kotlin acts more like using namespaces - unless explicitly wanted, nothing becomes an inner class with a reference to the outer class. This is actually very good. – Zordid Mar 08 '22 at 12:29