简体   繁体   中英

“lateinit property <varName> has not been initialized” when using WebTestClient with SpringBootTest on Kotlin

I can not figure out how to get the WebTestClient initialized when using Kotlin and Spring Boot Tests.

@ExtendWith(SpringExtension::class, MockKExtension::class)
@AutoConfigureWebTestClient
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GraphQlClientIntegrationTest {
    private val testToken = "aUna%14OkmUZunb528342"

    @Autowired
    lateinit var client: WebTestClient

    @InjectMockKs
    lateinit var gateGraphQlClient: GateGraphQlClient

    @Test
    fun shouldAddAuthorization() {
        val ID = Id(UUID.randomUUID().toString())
        val returnResult = client.post()
                .uri("/graphql")
                .header(HttpHeaders.AUTHORIZATION, testToken)
                .exchange()
                .expectStatus().isOk
                .returnResult(ObjectNode::class.java)
    }
}

This is the error message

lateinit property client has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property client has not been initialized

Try constructor injection. Because lateinit will initialize object lazily. So it will give null value when you call method so its throw UninitializedPropertyAccessException

class GraphQlClientIntegrationTest(val client: WebTestClient,
                                   val gateGraphQlClient: GateGraphQlClient) {
    private val testToken = "aUna%14OkmUZunb528342"
    // Your Code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM