Closed kirillzh closed 5 years ago
@kirillzh
Have you tried using onGeneric
?
Sry for not being sharp on this.
This is the correct answer I think:
interface Foo {
fun bar(): Single<out Bar<Int>>
}
sealed class Bar<T> {
data class A<T>(val a: T) : Bar<T>()
}
@Test
fun covariantTest() {
val foo = mock<Foo> {
on { bar() }.doReturn(Single.just(Bar.A(1)), Single.just(Bar.A(2)))
}
val obj = foo.bar().blockingGet()
val obj2 = foo.bar().blockingGet()
assertEquals(Bar.A(1), obj)
assertEquals(Bar.A(2), obj2)
}
You have to change the return type of your function to a covariant type.
@kirillzh Did the above solution work for you?
Yes, I ended up using Mockito's original thenReturn
as a workaround.
Code sample:
Received error:
Calling
thenReturn()
from original Mockito library however compiles just fine:It's seems that the type is getting lost along the way so I tried to define my own infix function with covariant type like so but that gave type mismatch:
I think the problem here is that
Single
doesn't have covariant type which doesn't allow us to establish relationship between the types. Initial code works as expected if theBar
value is being wrapped in something with covariant types, e.g. Kotlin'sList
:I'm not sure if that's
org.mockito:mockito-core
orcom.nhaarman:mockito-kotlin-kt
issue.Mockito:
org.mockito:mockito-core:2.7.5
Mockito Kotlin:com.nhaarman:mockito-kotlin-kt1.1:1.5.0
Kotlin:1.2.71
JDK: 1.8