mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 201 forks source link

capture throws InvalidUseOfMatchersException #24

Closed neworld closed 8 years ago

neworld commented 8 years ago

I have class:

class ApiError: RuntimeException {

    constructor(cause: Throwable) : super(cause) {
        errorType = ErrorType.SYSTEM
        retrofitResponse = null
        validationErrors = emptyList()
    }

    constructor(retrofitError: RetrofitError) : super(retrofitError) {
        when (retrofitError.kind) {
            RetrofitError.Kind.HTTP -> errorType = ErrorType.SERVER
            else -> errorType = ErrorType.SYSTEM
        }

        retrofitResponse = retrofitError.response
        validationErrors = emptyList()
        parseApiResponse(retrofitError)
    }
    ....
}

Test looks like:

private val onApiError: Function1<ApiError, Unit> = mock()
private val apiErrorCaptor: ArgumentCaptor<ApiError> = argumentCaptor()

@Test
fun test() {
  verify(onApiError).invoke(capture(apiErrorCaptor)) //<--throws here
}

And got exception:

Caused by: org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at com.vinted.data.rx.api.ApiObserverTest.testOnThrowedApiError(ApiObserverTest.kt:174)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

    at java.lang.Throwable.<init>(Throwable.java:311)
    at java.lang.Exception.<init>(Exception.java:102)
    at java.lang.RuntimeException.<init>(RuntimeException.java:96)
    at com.vinted.data.rx.api.ApiError.<init>(ApiError.kt:30)
    ... 57 more

I checked, ApiError is constructed well using ApiError(Throwable) constructor. Something bad happens with matchers.

For my surprise, #22 fixes that issue. But I don't understand how.

nhaarman commented 8 years ago

It seems to be caused by an internal interaction with a created unchecked mock. I have opened issue #27 for this.