javaandroidunit-testingkotlinkotlin-lateinit

Kotlin Unit Test variable declaration lateinit vs lazy vs nullable vs non-nullable


We are converting most of our unit tests from Java to Kotlin. What's the best way to declare a variable in our unit tests (across but not all some might still have use cases to use lateinit, lazy, nullable etc...) and why.


Solution

  • I believe lateinit, lazy, nullable and non-nullable are good features in Kotlin also in the unit test.

    you might know that lateinit is working only with var lateinit var, this gives the following features:

    1. you can initialize lateinit var from any part of the project, so this gives you the ability to initialize the variable maybe within your test case
    2. lateinit var doesn't work with non-nullable values, so you can assign a null value to lateinit variable and check its nullability as a test case.
    3. in lateinit var you can change the value frequently, and since you are changing values, it increases your test cases, hence your coverage.

    while in lazy, it works only with val, val ins by lazy{}

    I do recommend reading this article about best practice in kotlin.

    I hope this was good. 🤓