it is my first question so apologies if I did something wrong. I'm testing a usecase that takes an injected Lazy Dagger constructor parameter.
import dagger.Lazy
class TrackSpeed (val analyticsRepository: Lazy<AnalyticsRepository>) {
fun execute(timeMillis: Long) {
analyticsRepository.get().trackSpeed(timeMillis)
}
}
I don't know how to mock AnalyticsRepository as it is Lazy. This is how my test class looks right now:
class TrackSpeedTest {
private lateinit var trackSpeed: TrackSpeed
private val analyticsRepository: Lazy<AnalyticsRepository> = mock()
@Before
fun setUp() {
trackSpeed = TrackSpeed(analyticsRepository)
}
@Test
fun testTrackSpeed() {
val time: Long = 0
trackSpeed.execute(time)
verify(analyticsRepository.get(), times(1))
.trackSpeed(time)
}
There are no compilation errors but when I run the test it fails with this exception:
java.lang.ClassCastException: io.reactivex.internal.operators.flowable.FlowableError cannot be cast to com.package.AnalyticsRepository at com.package.TrackSpeed.execute()
Any suggestions? Thanks in advance.
You could create an actual instance of Lazy that returns your mocked AnalyticsRepository in get():
analyticsRepository = mock<AnalyticsRepository>()
val lazy = Lazy<AnalyticsRepository> { analyticsRepository }
trackSpeed = TrackSpeed(lazy)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With