【发布时间】:2021-08-30 02:03:23
【问题描述】:
我很抱歉就这个错误发了另一个帖子,但我仔细检查了另一个帖子并确保它不是同一个原因。
我有一个使用ExploreService 的ExploreRepository 类。存储库实现 NetworkBoundResource。我是单元测试仓库,使用 Mockito 来模拟 Service。
class ExploreRepository(
private val context: Context,
private val exploreService: ExploreService
) {
suspend fun getProperties(southwest: LatLng, northeast: LatLng, zoomLevel: Float): LiveResource<List<Property>> {
return object : NetworkBoundResource<List<Property>, SearchProperties>() {
override suspend fun makeApiCall(): SearchProperties {
println("exploreService hashcode ${System.identityHashCode(exploreService)}")
return exploreService.getProperties(context, geoHashList, precision)
}
}.asLiveResource()
}
我的 testExploreRepository 类
@Config(sdk = intArrayOf(Build.VERSION_CODES.O_MR1))
@RunWith(AndroidJUnit4::class)
class ExploreRepositoryTest {
...
// Subject under test
private lateinit var exploreRepository: ExploreRepository
// Use a fake service to be injected into the repository
private lateinit var mockExploreService: ExploreService
private lateinit var mockSearchProperties: SearchProperties
private val context: Application = ApplicationProvider.getApplicationContext()
@Before
fun setup(){
mockExploreService = mock()
exploreRepository = ExploreRepository(context, mockExploreService)
mockSearchProperties = mock()
}
@Test
fun `should make network service call`() = runBlocking<Unit> {
// stubbing
whenever(mockExploreService.getProperties(any(), any(), any())).thenReturn(mockSearchProperties)
val northeast = LatLng( 37.799001, -122.422889)
val southwest = LatLng( 37.782180, -122.451554)
val zoomLevel = 10f
exploreRepository.getProperties(southwest,northeast,zoomLevel)
println("exploreService hashcode ${System.identityHashCode(mockExploreService)}") // debug line
verify(mockExploreService, times(1)).getProperties(any(), any(), any())
}
}
我已经打印出 exploreService 的 hashCode。
makeApiCall() 中的println("exploreService hashcode ${System.identityHashCode(exploreService)}") 确实运行了。
而且我确保我在我的存储库中调用相同的模拟服务实例。
但是mockito仍然抛出Actually, there were zero interactions with this mock.
编辑:实际上在测试文件中,启用了 println() 调试行。错误消失了。没有它会抛出错误。有什么线索吗?
【问题讨论】:
标签: android unit-testing mockito