gpt4 book ai didi

android - Mockito 无法模拟/监视,因为 : - final class

转载 作者:行者123 更新时间:2023-12-05 00:13:08 25 4
gpt4 key购买 nike

我是 viewmodel 中的一个简单函数 getCreditReport,我试图在其中创建一个 API 调用存储库层
我想在 viewmodel 中测试 getCreditReport 以检查是否调用了 thge 存储库,但出现以下错误

   org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class com.example.clearscore.data.DataRepository
Mockito cannot mock/spy because :
- final class
我试过的
MainActivityViewModel
class MainActivityViewModel @Inject constructor(
//private val retroServiceInterface: RetroServiceInterface,
private val dataRepository: DataRepository
) : ViewModel() {
var creditReportLiveData: MutableLiveData<CreditReport>

init {
creditReportLiveData = MutableLiveData()
}

fun getCreditReportObserver(): MutableLiveData<CreditReport> {
return creditReportLiveData
}

fun getCreditReport() {
viewModelScope.launch(Dispatchers.IO) {
try {
val response = dataRepository.getCreditReport()
creditReportLiveData.postValue(response)
Log.d("data", response.toString())
} catch (e: IOException) {
Log.d("data", e.toString())
}
}
}
}
资料库
class DataRepository @Inject constructor(
private val retroServiceInterface: RetroServiceInterface
) {

suspend fun getCreditReport(): CreditReport {
return retroServiceInterface.getDataFromApi()
}
}
单元测试
@RunWith(MockitoJUnitRunner::class)
class MainActivityViewModelTest {
@Mock
private lateinit var dataRepository: DataRepository

@Mock
private lateinit var mainActivityViewModel: MainActivityViewModel

@Test
fun getCreditReport() {
runBlocking {
mainActivityViewModel.getCreditReport()
verify(dataRepository).getCreditReport()
}
}
}
依赖注入(inject)组件 - 如果这有帮助
@Singleton
@Component(modules = [RetroModule::class])
interface RetroComponent {

fun inject(mainActivityViewModel: MainActivityViewModel)

fun getMainactivityViewModel(): MainActivityViewModel
}
请建议我做错了什么
谢谢
R

最佳答案

请尝试添加此依赖项

testImplementation "org.mockito:mockito-inline:3.11.2"

关于android - Mockito 无法模拟/监视,因为 : - final class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68840524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com