Home > Enterprise >  Kotlin: Nested class unable to get access to outerclass variables
Kotlin: Nested class unable to get access to outerclass variables

Time:11-11

I'm new to Kotlin and have little experience with Java, so please bear with me. From what I've been able to research (here, for example), it appears that mockFoo should be accessible from the outer class, but IntelliJ is giving me an Unresolved Reference error.

@ExtendWith(MockKExtension::class)
class GetBazTest {
    @MockK
    private lateinit var mockFoo: FooClient

    @MockK
    private lateinit var mockBar: BarClient

    private lateinit var getBaz: GetBaz

    @BeforeEach
    fun setup() {
        getBaz = GetBaz(
            mockFoo,
            mockBar,
        )
    }

    @Test
    fun `it should do a thing`() {
        // some code to create expectedResult

        coEvery {
            mockFoo.getSomething(any())
        } answers {
            expectedResult
        }
    }


    @Nested
    @DisplayName("Tests for Xyz")
    class XyzTest {
        @Test
        fun `it should do a different thing`() {
            // some code to create expectedResult

            coEvery {
                mockFoo.getAThing(any()) // mockFoo gives Unresolved Reference error
            } answers {
                expectedResult
            }
        }
    }

}

It doesn't seem right that I would need to setUp mockFoo again in the inner class. How do I access the outer variables?

CodePudding user response:

Simply make XyzTest an inner class to grant him access to outer-class members

@Nested
@DisplayName("Tests for Xyz")
inner class XyzTest { ...
  • Related