Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid partial coverage with lateinit fields in Kotlin

Tags:

android

kotlin

I have an Android service written in Kotlin which I inject using Guice. It has lateinit fields which cannot be null, but they must be lateinit because I cannot use constructor injection.

Something around these lines:

class VibrationService : Service() {
    @Inject
    private lateinit var pm: PowerManager
    private lateinit var wakeLock: WakeLock

    override fun onCreate() {
        AlarmApplication.guice().injectMembers(this)
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VibrationService")
        wakeLock.acquire()
    }
}

Now when I create JaCoCo reports, all lines where any of the lateinit fields are accessed are marked as partially covered. I think Kotlin compiler adds some checks to the bytecode to make sure that fields are initialized before they are accessed.

Is there any way to disable these checks? I want my 100% coverage:-)

like image 822
Yuriy Kulikov Avatar asked Nov 07 '22 18:11

Yuriy Kulikov


1 Answers

Use the new kotlinx-kover Gradle plugin which is compatible with JaCoCo and IntelliJ.
It resolves the problem with inline functions. Hopefully, it will resolve your problem too.

plugins {
     id("org.jetbrains.kotlinx.kover") version "0.5.0"
}

Once applied, the plugin can be used out of the box without additional configuration.

Watch its YouTube announcement video and also track its roadmap from this youtrack issue.

like image 63
Mahozad Avatar answered Nov 14 '22 23:11

Mahozad