Is it possible to ignore !!. operator in Kotlin code when calculating test coverage? Sometimes I have a nullable variable which cannot be null in a lifecycle method, and if I use !!., then jacoco report says "1 of 2 branches missed". I don't know how to handle that easily
Yeah this is a valid one.
Even if we write a test that throws NPE, still it shows "1 of 2 branches missed".
Here is an example:
Say we have a piece of code like this
fun getMapValue(map: Map<String, Int?>, key: String): Int {
return map[key]!!
}
The possible tests that we can write for this are:
@Test
fun `verify getMapValue returns map value for a valid key`() {
val map = mapOf("a" to 1, "b" to 2)
val result = TestJacocoBranchCoverage().getMapValue(map, "a")
Assertions.assertEquals(result, 1)
}
@Test
fun `verify getMapValue throws NPE for an invalid key`() {
val map = mapOf("a" to 1, "b" to 2)
assertThrows<NullPointerException> { TestJacocoBranchCoverage().getMapValue(map, "c") }
}
map[key]!! this means return the value if not null else throw null pointer exception. So both the test should ideally cover the whole code.
But Jacoco still complaints about a missing branch.