Skip to content

Parameter specified as non null is null

Niek Haarman edited this page Feb 8, 2019 · 4 revisions

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)