junit Kotlin:嵌套类无法访问外部类变量

uyhoqukh  于 2022-11-11  发布在  Kotlin
关注(0)|答案(1)|浏览(190)

我是Kotlin的新手,对Java没有什么经验,所以请耐心听我说。从我所能研究的(例如here)来看,mockFoo应该可以从外部类访问,但是IntelliJ给了我一个Unresolved Reference错误。

@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
            }
        }
    }

}

在内部类中再次需要setUpmockFoo,这似乎不太对。我如何访问外部变量?

rhfm7lfc

rhfm7lfc1#

只需使XyzTest成为一个inner类,以授予他访问外部类成员的权限

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

相关问题