BRDroid
BRDroid

Reputation: 4388

How to return result in kotlin suspend function

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

enter image description here

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

Upvotes: 3

Views: 928

Answers (1)

Some random IT boy
Some random IT boy

Reputation: 8467

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 occupationparameter:

occupation = arrayListOf<String() // here you forgot to fully enclose <String>

Upvotes: 1

Related Questions