mockito-kotlin icon indicating copy to clipboard operation
mockito-kotlin copied to clipboard

Meaningful error when calling an unstubbed method with a non-nullable return type

Open Mahoney opened this issue 5 years ago • 3 comments

Mockito returns null for any invocation where no expectation was set up.

If the method return type is non-nullable in Kotlin you get an NPE at a point it shouldn't really be possible given the type system's guarantees.

It would be good if you got a meaningful exception ("Unexpected invocation of method < signature > which has a non-nullable return type with arguments < args > on mock < mock >") at the line the method was called.

package mockitotests

interface X {
  fun y(i: Int): String
}

class MockitoTest : StringSpec({

  "null safety" {

    val aMock: X = mock()

    val error = shouldThrow<Throwable> {
      aMock.y(3)
    }

    error.message shouldBe "Unexpected invocation of method fun mockitotests.X.y(kotlin.Int): kotlin.String which has non-nullable return type with arguments [3] on mock $aMock"
  }
})

Mahoney avatar Mar 01 '19 18:03 Mahoney

Had a crack at this, but I'm not sure it's possible because mockito can't distinguish between calls to the mock passed to given or when, when the default null return is necessary, and calls to the mock in actual test execution.

Mahoney avatar Mar 02 '19 16:03 Mahoney

I'm not sure it's possible because mockito can't distinguish between calls to the mock passed to given or when, when the default null return is necessary, and calls to the mock in actual test execution.

@Mahoney Exactly

bohsen avatar Mar 15 '19 10:03 bohsen

This is an interesting case and I'm willing to leave it open to see if there's a solution to be found, although I'm afraid earlier observations may have shown this impossible.

nhaarman avatar Jul 05 '19 13:07 nhaarman