Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Unit testing a function that takes a function as parameter

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()
    }
}
like image 898
Bohsen Avatar asked Mar 08 '18 08:03

Bohsen


People also ask

Can you pass functions as parameters in Kotlin?

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.

Can functions in Kotlin be assigned to variables?

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.

How do you mock a method in Kotlin?

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.

How do you use a function in Kotlin?

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 ().


1 Answers

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.

like image 86
Vincent Mimoun-Prat Avatar answered Nov 10 '22 07:11

Vincent Mimoun-Prat