Issue
I have a suspend function which makes an API call to get some data, I am trying to write a unit test for the dataRepository function.
How can I make my function return a RESULT which is expected from the apiServiceInterface
this is my unit test
@RunWith(MockitoJUnitRunner::class)
class MainActivityViewModelTest {
@get:Rule
val coroutineRule = MainCoroutineRule()
@Mock
private lateinit var dataRepository: DataRepository
@Mock
private lateinit var dataObserver: Observer<Result<List<Character>>>
@InjectMocks
private lateinit var mainActivityViewModel: MainActivityViewModel
@Test
fun fetchCharacters() {
runBlockingTest {
Mockito.`when`(dataRepository.getCharacters())
.thenReturn( arrayListOf(Character(
name = "myName",
img = "image",
occupation = arrayListOf<String(),
status = "status",
nickname = "nickName",
appearance = arrayListOf<Int>()
)))
mainActivityViewModel.fetchCharacters()
verify(dataRepository).getCharacters()
Mockito.verify(dataObserver).onChanged(Result.success(listOf(Character (
name = "myName",
img = "image",
occupation = arrayListOf(),
status = "status",
nickname = "nickName",
appearance = arrayListOf()
))))
mainActivityViewModel.charactersLiveData.removeObserver(dataObserver)
}
}
}
error message
DataRepository
class DataRepository @Inject constructor(
private val apiServiceInterface: ApiServiceInterface
) {
suspend fun getCharacters(): Result<ArrayList<Character>> = kotlin.runCatching{
apiServiceInterface.getDataFromApi()
}
}
APiServiceInterface
interface ApiServiceInterface {
@GET("api/characters")
suspend fun getDataFromApi(): ArrayList<Character>
}
Can you suggest how I can fix this please
Thanks R
Solution
As @CommonsWare pointed out you need to wrap that into a Result
you may just do that by:
Result.success(arrayListOf(
…
))
Please also note that on the image you posted have a syntax error when you're defining the occupation
parameter:
occupation = arrayListOf<String() // here you forgot to fully enclose <String>
Answered By - Some random IT boy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.