Pablo Schmid
12/16/2021, 7:50 PMabstract 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
private val myVariable = mock<MyClassImpl>().also {
whenever(it.execute(any(), anyOrNull()).thenReturn(any())
}
Really appreciate the help.mkrussel
12/16/2021, 8:18 PMany()
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.
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.mkrussel
12/16/2021, 8:22 PMexecute
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.Pablo Schmid
12/16/2021, 8:30 PMmkrussel
12/16/2021, 8:31 PMPablo Schmid
12/16/2021, 9:19 PM