eendroroy
eendroroy

Reputation: 1511

How to access lateinit variable from companion object in SprintBoot test in kotlin?

I have a test class like following:

@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserControllerTest{
    @Qualifier("userRepository")
    @Autowired
    private lateinit var userRepository: UserRepository

    companion object {
        @JvmStatic
        @AfterClass
        @Throws(Exception::class)
        fun cleanupAll() {
        }
    }

    @Test
    @Throws(Exception::class)
    fun testUserShouldBeCreated() {
//        Some Test
    }
}

How do I access userRepository from cleanupAll method?

I have tried with:

companion object {
    @JvmStatic
    @AfterClass
    @Throws(Exception::class)
    fun cleanupAll() {
        UserControllerTest().userRepository.deleteAll()
    }
}

It gives the error:

kotlin.UninitializedPropertyAccessException: lateinit property userRepository has not been initialized

Upvotes: 1

Views: 1418

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

The problem actually has nothing to do with lateinit.

Your cleanupAll creates a new UserControllerTest. So it wouldn't do anything with the UserRepository used in the test even if it worked.

For this specific case, if a single userRepository should be shared between all tests, it should be declared in the companion object as well; if it shouldn't, then the cleanup method should be in the class, not the companion object.

Upvotes: 2

Related Questions