I have a function with a prototype similar to:
class objectToMock {
fun myFunc(stringArg: String, booleanArg: Boolean = false, functionArg: (String) -> Any = { 0 }): String
}
I'd like to be able to stub myFunc
but can't figure out how to. Something like
@Mock
lateinit var mockedObject: ObjectToMock
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
`when`(mockedObject.myFunc(anyString(), anyBoolean(), any())).thenReturn("")
}
Using any()
and notNull()
both lead to java.lang.IllegalStateException: any() must not be null
Mockito has been around since the early days of Android development and eventually became the de-facto mocking library for writing unit tests. Mockito and Mockk are written in Java and Kotlin, respectively, and since Kotlin and Java are interoperable, they can exist within the same project.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
What are Matchers? Matchers are like regex or wildcards where instead of a specific input (and or output), you specify a range/type of input/output based on which stubs/spies can be rest and calls to stubs can be verified. All the Mockito matchers are a part of 'Mockito' static class.
Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.
The solution here is to use anyOrNull
from https://github.com/nhaarman/mockito-kotlin, or implement that helper yourself.
Mockito often returns null
when calling methods like any()
, eq()
etcetera. Passing these instances to methods that are not properly mocked, can cause NullPointerExceptions
see: https://github.com/nhaarman/mockito-kotlin/wiki/Parameter-specified-as-non-null-is-null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With