Cast exception when mocking kotlin lambda callbacks in Mockk

青春壹個敷衍的年華 提交于 2021-01-29 18:54:26

问题


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

回答1:


Oops, I was misreading the error.

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

This method works, the cast exception was from the second line. The correction looks like

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


来源:https://stackoverflow.com/questions/53808565/cast-exception-when-mocking-kotlin-lambda-callbacks-in-mockk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!