我正在尝试使用declareMock
和mockk
模拟存储库类,但它似乎不起作用,因为我从真实存储库获取数据。
版本
implementation "org.koin:koin-androidx-viewmodel:2.1.6"
testImplementation "org.koin:koin-test:2.1.6"
法典
我的应用程序类(仅相关部分(:
class MyApplication : Application() {
companion object {
val appModule = module {
single<RepositoryUserLists> { RepositoryUserListsImpl() }
}
}
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@MyApplication)
modules(appModule)
}
}
}
我的测试类(仅相关部分(
class TestRepositoryUserLists : KoinTest {
@get:Rule
val koinTestRule = KoinTestRule.create {
modules(MyApplication.appModule)
}
@get:Rule
val mockProvider = MockProviderRule.create { clazz ->
mockkClass(clazz.java.kotlin)
}
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
private val repo: RepositoryUserLists by inject()
@Before
fun before() {
declareMock<RepositoryUserLists> {
every { getAllLists() } returns MutableLiveData(listOf(MyList("test list")))
}
//PROBLEM IS HERE
//Expected: a list containing one item names "test list".
//Actual: empty list (like in real repository).
repo.getAllLists().value
}
}
GitHub 问题:https://github.com/InsertKoinIO/koin/issues/841
只是在这里发布了它,供那些迁移到较新版本的koin(如2.2.2(的人使用, 并且依赖关系测试失败,错误Missing MockProvider. Please use MockProvider.register() to register a new mock provider
。
import io.mockk.every
import io.mockk.mockkClass
...
val app = koinApplication {
printLogger(Level.DEBUG)
modules(...)
}
MockProvider.register { mockkClass(it) }
with(app.koin) {
declareMock<MyService> {
every { someAction() } returns "some answer"
...
}
}
app.checkModules()
我认为您需要在declareMock
块中使用given/will
语法
declareMock<RepositoryUserLists> {
given(getAllLists()).willReturn(MutableLiveData(listOf(MyList("test list"))))
}