Put "open" to your class and its method when you get a NullPointerException by mocking your class by Mockito.
Problem
When you have MyClass and try to write a test by mocking MyClass as the following, you will get an NPE:
MyClass:
open class MyClass { fun createList(string: String): List<String> { return listOf("A", "B", "C", string) } }
Mocking MyClass by Mockito:
import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever class TestMyClass { @Test fun testMyClass() { val mock = mock<MyClass>() whenever(mock.createList(any())).thenReturn(emptyList()) } }
Exception you will get:
java.lang.NullPointerException: Parameter specified as non-null is null: method MyClass.createList, parameter string
Solution: Put "open" not only to your class but also to the method
open class MyClass { + open fun createList(string: String): List<String> { - fun createList(string: String): List<String> { return listOf("A", "B", "C", string) } }