Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mockito doAnswer in Kotlin

what would be the Kotlin equivalent to this Java code?

doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Design design = new Design();
        GetDesign.Listener callback = (GetDesign.Listener) invocation.getArguments()[0];
        callback.onSuccess(design);
        return null;
    }
}).when(someRepository).getDesign(any(GetDesign.Listener.class));

[UPDATE] After trying several options, I finally made it work using mockito-kotlin. I think that's the most comfortable way of implementing doAnswer. Syntax remains almost the same:

doAnswer {
    callback = it.arguments[0] as GetDesign.Listener
    callback.onSuccess(Design())
    null
}.whenever(someRepository).execute(any(GetDesign.Listener::class.java))

Complete code and build.gradle configuration can be found here

like image 590
voghDev Avatar asked May 19 '17 09:05

voghDev


1 Answers

doAnswer {
    val design = Design()

    val callback = it.arguments[0] as GetDesign.Listener
    callback.onSuccess(design)

    null // or you can type return@doAnswer null

}.`when`(someRepository).getDesign(any(GetDesign.Listener::class.java))
like image 53
Anton Holovin Avatar answered Sep 19 '22 06:09

Anton Holovin