问题
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