mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 202 forks source link

mocking methods that depend on parameters passed to them #467

Closed sarimmehdi closed 1 year ago

sarimmehdi commented 1 year ago

I am new to Mockito so I apologize if I don't get the general philosophy of this library. Documentation on this for the java version of mockito also doesn't really explain how to mock methods where the returned result depends on the parameters passed to the method. Below is the method I am trying to mock:

override suspend fun getComics(
    numsOfComicsToLoad: List<Int>,
    loadFromDatabase: Boolean
): Flow<Resource<List<Comic>>> = flow {
    emit(Resource.Loading())
    val comics = if (loadFromDatabase) {
        comicsInDatabase.filter { comic -> comic.num in numsOfComicsToLoad }
    } else {
        comicsInApi.filter { comic -> comic.num in numsOfComicsToLoad }
    }
    emit(Resource.Success(comics))
}

here's my attempt at trying to mock the above method (it is part of the repository class)

repository = mock {
    onBlocking { getComics(anyArray<Int>().toList(), any()) } doReturn flow {
        emit(Resource.Loading())
        // what do I do now????
    }
}

Any help regarding this would be appreciated

TimvdLippe commented 1 year ago

You can use Answer to implement custom logic: https://stackoverflow.com/questions/44066993/using-mockito-doanswer-in-kotlin

sarimmehdi commented 1 year ago

I am adding my code here for anyone else running into the same problem:

repository = mock {
    onBlocking { getAllComics() } doReturn flow {
        emit(Resource.Loading())
        emit(Resource.Success(comicsInDatabase))
    }
    onBlocking { getComics(any(), any()) } doAnswer {
        flow {
            val numsOfComicsToLoad = it.getArgument(0) as List<Int>
            val loadFromDatabase = it.getArgument(1) as Boolean
            emit(Resource.Loading())
            val comics = if (loadFromDatabase) {
                comicsInDatabase.filter { comic -> comic.num in numsOfComicsToLoad }
            } else {
                comicsInApi.filter { comic -> comic.num in numsOfComicsToLoad }
            }
            emit(Resource.Success(comics))
        }
    }