Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 989
Steven Jeuris Avatar asked Mar 08 '18 19:03

Steven Jeuris


2 Answers

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.

like image 142
Steven Jeuris Avatar answered Sep 17 '22 02:09

Steven Jeuris


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.

like image 27
Marc Philipp Avatar answered Sep 19 '22 02:09

Marc Philipp