Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Lazy constructor parameter

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.

like image 780
Freesko Avatar asked Aug 24 '18 08:08

Freesko


Video Answer


1 Answers

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)
like image 66
Dominik G. Avatar answered Oct 10 '22 21:10

Dominik G.