0

I am having some trouble mocking callback functions with Mockk.

I am trying to mock a task success listener that is called like this:

collection
    .add(Item())
    .addOnSuccessListener {
        update(collection.document(it.id))
    }

Where the java signature for the callback would look like this:

public interface OnSuccessListener<T> {
    void onSuccess(T var1);
}

and the signature for addOnSuccessListener looks like this

public abstract Task<DocumentReference> addOnSuccessListener(@NonNull OnSuccessListener<DocumentReference> var1);

My mock looks like this:

every { documentReferenceTask.addOnSuccessListener(any()) } answers {
    firstArg<(DocumentReference) -> Unit>().onSuccess(documentReference)
    value
}

I have also tried:

every { documentReferenceTask.addOnSuccessListener(any()) } answers {
    firstArg<OnSuccessListener<DocumentReference>>().invoke(documentReference)
    value
}

Either way, I am receiving a cast exception like:

java.lang.ClassCastException: com.package.MyClass$addProduct$1 cannot be cast to kotlin.jvm.functions.Function1
4

1 回答 1

1

糟糕,我误读了错误。

every { documentReferenceTask.addOnSuccessListener(any()) } answers {
    firstArg<OnSuccessListener<DocumentReference>>().invoke(documentReference)
    value
}

此方法有效,强制转换异常来自第二行。修正看起来像

every { documentReferenceTask.addOnSuccessListener(any()) } answers {
    firstArg<OnSuccessListener<DocumentReference>>().invoke(documentReference)
    **documentReferenceTask**
}
于 2018-12-17T05:04:25.070 回答