Unit testing folks! Consider this scenario, where ...
# test
a
Unit testing folks! Consider this scenario, where I have to unit test this method
Copy code
fun groupByWeek(listItems: List<Item>, dateUtils: DateUtils): Map<Int, MutableList<Item>> {
        val dateResponseMap = mutableMapOf<Int, MutableList<Item>>()

        listItems.forEach { response ->
            val date = dateUtils.getWeekOfCurrentYear(response.time)
            date?.let {
                if (!dateResponseMap.containsKey(date)) {
                    dateResponseMap[date] = mutableListOf()
                }

                dateResponseMap[date]?.add(response)
            }
        }
        return dateResponseMap
    }
Question here is to mock or not to mock
DateUtils
class.
DateUtils
is our custom class which is already Unit Tested. Not mocking it is not ideal but it saves a lot of trouble (note the usage of
dateUtils.getWeekOfCurrentYear()
inside loop).
listItems
here are coming from a fake repository.
response.time
is
long
timestamp. Is there a better(more testable) way of writing this method?
n
I’d say it depends on what getWeekOfCurrentYear does. From the name, getWeekOfCurrentYear looks as if it depends on the current time — eg on the system clock — in which case I would pass in a fake version for which the current time is controlled by the test. But from the parameter it looks like it may be a pure function that only depends on its argument. In which case, I’d not mock it. I’d either pass the function in, or just define the function at the top level (eg not have a dateUtils object) and call it directly.
a
Yes that method depends only on argument. Thanks for your input.