我有关于使用Mockito和Koin依赖注入的单元测试的问题,我想测试ViewModel,我已经注入并模拟了类服务和存储库,但是在运行测试错误there were zero interaction...
时,该代码如下:>
class HomeViewModelTest: KoinTest {
val scope = CoroutineScope(Dispatchers.Unconfined)
val repository: NewsRepository by inject { parametersOf(scope) }
val service by inject<Service>()
@Mock
lateinit var showLoading: Observer<Boolean>
@Mock
lateinit var newsList: Observer<List<Article>>
@Mock
lateinit var showError: Observer<String>
@get:Rule
val rule = InstantTaskExecutorRule()
lateinit var server: MockWebServer
@Before
fun setUp() {
server = MockWebServer()
server.start()
BASE_TEST_URL = server.url("/").toString()
MockitoAnnotations.initMocks(this)
startKoin { modules(listOf(appTestModule)) }
declareMock<NewsRepository>()
declareMock<Service>()
}
@Test
fun getNewsTest() = runBlocking {
verify(service, times(1)).getSources(apiKey = API_KEY)
val sources = arrayListOf<Source>()
val dataResponse = SourceResponse(sources, "200")
val response = Response.success(dataResponse)
`when`(service.getSources()).thenReturn(response)
val resultCallback = argumentCaptor<(List<Article>?, String?) -> Unit>()
Mockito.verify(repository).getNewsList(id = eq("us"), response = resultCallback.capture())
}
@After
fun tearDown() {
stopKoin()
}
}
和这样的类存储库:
class NewsRepository(private val scope: CoroutineScope) : KoinComponent {
private val service by inject<Service>()
fun getSource(response: (List<Source>?, String?) -> Unit) {
request(
scope,
{service.getSources()}, { res ->
when(res) {
is Result.Success -> response(res.data.sources, null)
is Result.Failure -> response(null, res.error)
}
})
}
}
但是此错误显示在验证类HomeViewModelTest
中,我试图禁用verify(service)
行中的verify(repository)
显示错误,并引用了方法request
中的行getSource
在NewsRepository
上,有人可以解决我的问题,我是有关单元测试的初学者