mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 202 forks source link

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

Open Mahoney opened 5 years ago

Mahoney commented 5 years ago

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 commented 5 years ago

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.

bohsen commented 5 years ago

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

nhaarman commented 5 years ago

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.