Hello, i have a problem with mockin a List of mock...
# mockk
d
Hello, i have a problem with mockin a List of mock. I’m tring to mock this type:
Copy code
@MockK
lateinit var mockAnalyticsReporters: List<AnalyticsReporter?>
when using this I recieve this strange error:
class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')
java.lang.ClassCastException: class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')
at io.mockk.renamed.java.util.Iterator$Subclass5.hasNext(Unknown Source)
I actually can’t understand what this means. I’m not a very well tester so i need some help. Thanks.
m
that error message doesn’t seem related to the mock instantiation, but rather to casting something to Boolean
d
Yes but I don’t have anything that matches that return type. I mean, i use that mock in this way:
Copy code
coEvery { mockAnalyticsReporters.logAnalyticEvent(mockEvent) } answers { }
where`mockEvent` is :
Copy code
@MockK
lateinit var mockEvent : AnalyticsEvent
the method is an extension function made like this:
Copy code
fun <T : AnalyticsReporter> List<T?>.logAnalyticEvent(event: AnalyticsEvent) = forEach { reporter ->
        reporter?.logEvent(event)
    }
m
that empty
answers
block doesn’t look right to me does
logAnalyticEvent
return Boolean?
i’m guessing it does, and if it does, when you mock the method you should be returning a Boolean in the
answers
block
d
actually as you can see in the method above that method returns Unit.
also the last line of the stack trace seems related to something mockk does:
at io.mockk.renamed.java.util.Iterator$Subclass5.hasNext(Unknown Source)
m
also I don’t really see the point of mocking a List maybe what you want to do is building a list of mocks
I mean, I don’t think what you want to test is that the
List
class behaves as you expect
d
Ok, i have to test the code in which this list is called and is a dependency so i have to mock a list. Even without a @MOckk annotation that code returns that problem.. The ext function reciever is a list so I have to mock that list. I actually suspect that the problem could be the List and the forEach. but it’s jsut a guess.
m
what I’m saying is that IMHO your mock should be something like
val mockAnalyticsReporters = listOf(mockk<AnalyticsReporter>())
d
Ok, thanks. I’ll try it.
k
The function you're trying to test is defined like this:
Copy code
fun <T : AnalyticsReporter> List<T?>.logAnalyticEvent(event: AnalyticsEvent) = forEach { ... }
and the
forEach
call relies on the receiver list's iterator's
hasNext
. But you've mocked that receiver and haven't told the mock what to do with
iterator()
and
hasNext()
.
👍 1
d
@Klitos Kyriacou oh, i see…thanks for the explanation. I will look better into it. 🙂