I have a function that retrieves a list of items from a repository. Instead of using a regular callback I pass in a function and invoke this with the result. But how can you unittest this kind of function. Is there some way to verify that the passed in function is being invoked or should I refactor and use a regular callback and test it using a mocked callback-interface?
My code:
class WorklistInteractor @Inject
constructor(private val worklistRepository: WorklistRepository,
private val preferenceManager: PreferenceManager,
private val executor: Executor)
: WorklistDialogContract.Interactor, Executor by executor {
@Volatile private var job: Job? = null
override fun getWorklist(callback: (Result<List<WorklistItem>>) -> Unit) {
job = onWorkerThread {
val result = worklistRepository.getWorklist().awaitResult()
onMainThread { callback(result) }
}
}
override fun cancel() {
job?.cancel()
}
}
In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.
Kotlin functions are first-class, which means they can be stored in variables and data structures, and can be passed as arguments to and returned from other higher-order functions.
mockk:mockk supports to mock top-level functions in Kotlin. Similar to extension functions, for top-level functions, Kotlin creates a class containing static functions under the hood as well, which in turn can be mocked.
Now that you have created a function, you can execute it by calling it. To call a function in Kotlin, write the name of the function followed by two parantheses ().
To check it is called, something like that would work:
var hasBeenCalled = false
interactor.getWorklist({ result -> hasBeenCalled = true })
assertTrue(hasBeenCalled)
Of course you could also check that the expected result is passed, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With