简体   繁体   中英

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.

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

  • This is a good practice when you have a singleton (object class) and your test cases are dependant on this instance, so you create it once by lazy

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

I hope this was good. 🤓

Below is the use:

Safe calls(?.): This helps to avoid the NullPointerException. It calls method/property with the help of an object if that object is not null, else returns null (Not NPE). This is simply a null check.

The !! Operator: This is used to explicitly assert that property is not null. But if it is null then it throws NullPointerException

Lateinit: Using lateinit, the initial value does not need to be assigned. We can initialize it later. We don't need to initialize anything until we need it.

This is just a short explanation for more details I found below blogs useful, please check: https://medium.com/@agrawalsuneet/safe-calls-vs-null-checks-in-kotlin-f7c56623ab30 https://www.bignerdranch.com/blog/kotlin-when-to-use-lazy-or-lateinit/

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