- 
                Notifications
    
You must be signed in to change notification settings  - Fork 206
 
Parameter specified as non null is null
        icguy edited this page Jan 22, 2025 
        ·
        5 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)
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())
}