Reputation: 4388
I am a simple function getCreditReport in viewmodel in which I am trying to make an API call repository layer I want to test getCreditReport in viewmodel to check that thge repository is called but I get the following error
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.example.clearscore.data.DataRepository
Mockito cannot mock/spy because :
- final class
What I have tried
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())
}
}
}
}
DataRepository
class DataRepository @Inject constructor(
private val retroServiceInterface: RetroServiceInterface
) {
suspend fun getCreditReport(): CreditReport {
return retroServiceInterface.getDataFromApi()
}
}
Unit test
@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()
}
}
}
Dependency Injection component - in case this is helpful
@Singleton
@Component(modules = [RetroModule::class])
interface RetroComponent {
fun inject(mainActivityViewModel: MainActivityViewModel)
fun getMainactivityViewModel(): MainActivityViewModel
}
Please suggest what I am doing wrong
Thanks R
Upvotes: 10
Views: 35503
Reputation: 1598
[Adding to help future folks who stumble upon this question]
In my case, the class didn't need to be final so I just removed final
from the class declaration.
Upvotes: -1
Reputation: 321
Please try adding this dependency
testImplementation "org.mockito:mockito-inline:3.11.2"
Upvotes: 28