Skip to content

Parameter specified as non null is null

Joshua Selbo edited this page Nov 18, 2025 · 6 revisions

Note: As of Mockito 5.0 release, the inline mock maker is the default and the limitations here don't apply.


Mockito often returns null when calling methods like any(), eq() etcetera. Passing these instances to methods that are not properly mocked, can cause NullPointerExceptions:

open class Foo {
  fun bar(s: String) { }
}

@Test
fun myTest() {
  whenever(foo.bar(any())) // This fails, since null is passed to bar.
}

Since the bar method is not marked open, it is final and Mockito cannot mock it. As a consequence, the method is executed when calling bar(any()). Since Kotlin inserts null-checks, an NPE is thrown.

To solve this, mark bar as open or use mock-maker-inline.
(warning: inline mocking has a ~3x performance penalty)

Another way of solving this is by defining the mock with the following syntax:

open class Foo {
  fun bar(s: String) { }
  fun baz(s: String): String { return "original" }
}

@Test
fun myTest() {
  // this fails
  // whenever(foo.baz(any())).thenReturn("mocked")

  // these work
  doReturn("mocked").whenever(foo).baz(any())
  doNothing().whenever(foo).bar(any())
}

Clone this wiki locally