dimanche 14 avril 2019

Test closure of an extension function in Kotlin

Suppose we have the following code:

@ExperimentalCoroutinesApi
fun ProducerScope<DownloadableDataDto<out User>>.findInteresting(input: ReceiveChannel<DownloadableDataDto<out User>>,
                                                                 communitiesCount: Int,
                                                                 userCountMap: MutableMap<User, Int> = ConcurrentHashMap()) = createProducer(input) {
    if (userCountMap.compute(it.data!!) { _, value ->
                if (value == null) 1 else value + 1
            } == communitiesCount) send(it)
}

This code checks if a user is a part of all of the communitiesCount communities. But this logic is enclosed inside a createChannel() higher order function, which I would not want to test at the moment. Is there a way to test only the internals? I assume I could probably extract that to a separate function as well, right?

And if I do it that way, let's say we have this instead:

@ExperimentalCoroutinesApi
fun ProducerScope<DownloadableDataDto<out User>>.findInteresting(input: ReceiveChannel<DownloadableDataDto<out User>>,
                                                                 communitiesCount: Int,
                                                                 userCountMap: MutableMap<User, Int> = ConcurrentHashMap()) = createProducer(input) {
    sendIfInteresting(it, communitiesCount, userCountMap)
}

@ExperimentalCoroutinesApi
private suspend fun ProducerScope<DownloadableDataDto<out User>>.sendIfInteresting(userDto: DownloadableDataDto<out User>,
                                                                                   communitiesCount: Int,
                                                                                   userCountMap: MutableMap<User, Int>) {
    if (userCountMap.compute(userDto.data!!) { _, value ->
                if (value == null) 1 else value + 1
            } == communitiesCount) send(userDto)
}

How would I mock the send(userDto) call? I can mock the ProducerScope object, but how would I call the real sendIfInteresting() method?

Aucun commentaire:

Enregistrer un commentaire