Hello, I have a function that uses generic that I ...
# getting-started
p
Hello, I have a function that uses generic that I would like to mock using mockito.
Copy code
abstract class MyClass<T>(){
    abstract fun blocking(): T

fun <R> execute(run: (T)->R, onError: ((e: Throwable)->R)? = null): R {
        return runCatching { run(blocking()) }.getOrElse{ e -> onError?.let { it(e) } ?: throw e}
}
}

internal class MyClassImpl(): MyClass<String>() {
    override fun blocking(): String {
        return "something"
    }
}
I would like to mock the execute function in MyClassImpl that extends MyClass I usually mock functions as follows but it's not compiling as it can't infer the types
Copy code
private val myVariable = mock<MyClassImpl>().also {
        whenever(it.execute(any(), anyOrNull()).thenReturn(any())
    }
Really appreciate the help.
m
First i don't think you should be passing
any()
into
thenReturn
. The mock needs to return a specific value. Then I think you need to specify the version of execute you are trying to mock.
Copy code
mock<MyClassImpl>().also {
        whenever(it.execute<String>(any(), anyOrNull()).thenReturn("Expected Return Value")
    }
This would unfortunately return the String even if execute is called for a different generic.
I would also probably avoid mocking this class. By mocking
execute
you are mocking away the use of all the client code that is being passed into
execute
. That seems like you are then skipping a lot of code in the unit under test. Would seem better instead to mock the
blocking
function and let
execute
do its thing.
p
the problem with that is that blocking and execute are part of the same mocked class, so I need to mock execute too
m
You could do spy instead of a mock. I also think there is a way to configure Mockito to call the real method for methods that you don't mock, but I haven't played with that in a long time.
p
Spy along with mocking blocking works! Thanks!