I'm trying to perform UI instrumentation tests and mock my repository's return method loadSensors(), but it throws me an error in SensorsTest class every { } call. I could not find an appropriate solution on how to use MockK together with Hilt, when I have fake dependencies injected via TestInstallIn. I have tried @Inject, @Mockk, @InjectMockKs for the repository variable in the test class, but I still receive the same error. This repository is injected in the ViewModel.
io.mockk.MockKException: Failed matching mocking signature for
left matchers: [any(), any()]
at io.mockk.impl.recording.SignatureMatcherDetector.detect(SignatureMatcherDetector.kt:99)
at io.mockk.impl.recording.states.RecordingState.signMatchers(RecordingState.kt:39)
at io.mockk.impl.recording.states.RecordingState.round(RecordingState.kt:31)
at io.mockk.impl.recording.CommonCallRecorder.round(CommonCallRecorder.kt:50)
at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:63)
at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:30)
at io.mockk.MockKDsl.internalEvery(API.kt:93)
at io.mockk.MockKKt.every(MockK.kt:98)
Test class
@HiltAndroidTest
class SensorsTests {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var repository: MockRepositoryImpl
@Before
fun before() {
MockKAnnotations.init(this)
hiltRule.inject()
every { repository.loadSensors(any(), any()) } answers {
lastArg<(Result<MutableList<UserSensor>>) -> Unit>().invoke(
Result.Success("", mutableListOf(UserSensor(0), UserSensor(1)))
)
}
ActivityScenario.launch(MainActivity::class.java)
}
@Test
fun userSensorsAreVisible() {
Thread.sleep(10000)
// TODO: check if provided sensors are visible
}
}
MockRepositoryImpl class
class MockRepositoryImpl @Inject constructor() : Repository {
override fun loadSensors(userId: String, param: (Result<MutableList<UserSensor>>) -> Unit) {
// Blank
}
// ...
}
MockAppModule class
@Module
@TestInstallIn(
components = [ViewModelComponent::class],
replaces = [AppModule::class]
)
abstract class MockAppModule {
@Binds
abstract fun bindRepositoryImpl(repositoryImpl: MockRepositoryImpl): Repository
// ...
}