https://kotlinlang.org logo
#test
Title
# test
s

Simon Lin

01/07/2021, 9:53 AM
How do I test the
init block
? the sample:
Copy code
class Foo() {
    init {
        loadData()
    }

    private fun loadData() {
        repository.getData()
    }
}
And this is what I done. Is it correct?
Copy code
class FooTest {

    private val foo by lazy { Foo() }

    @Test
    fun `test foo init block`() {

        foo // access foo to create an instance by Lazy 

        coVerify(exactly = 1) { repository.getData() }
    }
}
t

tddmonkey

01/07/2021, 10:18 AM
Why would you? It appears to have no effect
d

Daniel

01/07/2021, 10:37 AM
Best don't use lazy in tests. Since you want a fresh instance of it in each test. So either create it in @Before or use @InjectMocks as the alternative
e

Emil Kantis

01/09/2021, 10:49 AM
I would prefer to mock the response of
repository.getData()
and verify that the data has been loaded as expected, if possible 🙂
56 Views