https://kotlinlang.org logo
#android
Title
# android
s

Shoaib khalid

11/10/2023, 9:26 PM
Do anyone knows how can i mock a void method with callback argument in mockito? Any useful example? I'm so fed up with chatgpt wrong answers. void test(callback:(Long) -> Unit)
m

Manish malviya

11/11/2023, 7:08 AM
You can use ArgumentCaptor
👀 1
s

Shoaib khalid

11/11/2023, 7:09 AM
Thanks @Manish malviya, I'm looking into it.
👍 1
Copy code
`when`(favoriteRepo.addFlutterFavorite(any(), any())).thenAnswer {
    val callback = it.arguments[1] as (Long) -> Unit
    callback(100L)
}


favoriteRepo.addFlutterFavorite(null) { result ->
    assert(result == 100L)
}
The above testcase passed means the callback value is 100 which i gave in thenAnswer block for
addFlutterFavorite()
but the problem is if an other method calls
addFlutterFavoite()
then the it's callback never executes in my actual code but in above test case the callback works fine. @Manish malviya can you please identify any mistake or any suggestion? thanks
I don't know what was wrong in above code but after using argumentCaptor it's working fine.
Copy code
val argumentCaptor = argumentCaptor<(Long) -> Unit>()


        `when`(favoriteRepo.addFlutterFavorite(Mockito.any(), argumentCaptor.capture())).thenAnswer {
            argumentCaptor.firstValue.invoke(100L)
        }
m

Manish malviya

11/11/2023, 7:46 AM
@Shoaib khalid i will need more context to answer your question, since what i can see is you are testing your callback 🤔 from above code i can see favouriteRepo is a mock and when its called you are asserting the value on the mock itself
I don’t remember exactly but but you are passing a callback lets say from viewmodel to your repo, but your repo is a mock so we need to capture the argument using ArgumentCaptor and then you can mock your lambda
I will suggest if your using this callback for asynchronous call use it using suspend and if its to return multiple values use flow
👍 1