Ravkiran, your example can be reduced to
private fun example(x: Any?) {
x!!
}
fun main(args: Array<String>) {
example("")
try {
example(null)
} catch (e: NullPointerException) {
}
}
Anyway thank you both for these valuable inputs!
Inability to cover case of exception seems to be related to widely known
JaCoCo limitation - see for example
https://stackoverflow.com/a/54034393/244993 that refers to
https://www.jacoco.org/jacoco/trunk/doc/faq.html "Source code lines with
exceptions show no coverage. Why?" , because
x!!
compiles into something like
if (x == null) kotlin.jvm.internal.Intrinsics.throwNpe()
So even if one can question whether this branch needs to be tested or not
(and hence shown as covered or not), as of now due to above limitation
anyway seems better to implement filter
- https://github.com/jacoco/jacoco/pull/802
Regards,
Evgeny
On Saturday, January 5, 2019 at 12:01:37 AM UTC+1, [email protected]
wrote:
>
> On Friday, 4 January 2019 14:44:00 UTC-8, [email protected] wrote:
> > On Wednesday, 26 December 2018 11:14:32 UTC-8, [email protected] wrote:
> > > E.g. a jpa entity has a nullable field ID to be able to be saved. If I
> request the entity from a repository which returns only saved entities,
> then I have to use !!. operator to reference id values.
> > > Generally, such cases often occur when dealing with
> lifecycle-dependent objects. I usually set a variable nullable to:
> > > * to force programmers to pay attention when using it
> > > * to make it possible to release memory by nullifying the variable
> >
> > 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.
>
>
--
You received this message because you are subscribed to the Google Groups
"JaCoCo and EclEmma Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/jacoco/d795a5ab-c0e1-4d54-8013-bbfacababc9f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.