Android Unit Test Mockito returns null

782 Views Asked by At

I'm using Mockito for unit testing.

I want to test my usecase and with mock repository but there's some problem.

I had my repository's function returns arraylist by using mockito. (here's code below)

`when`(mockRepository.searchByKeyword(request.auth, request.keyword)).thenReturn(myArrayList)

And created usecase with the mock repository. (here's code below too)

 val useCase = SearchProjectUseCase(
    mockRepository, coroutineRule.testDispatcher
 )

SearchUseCase's code below.

class SearchProjectsUseCase(
    private val projectRepository: ProjectRepository,
    coroutineDispatcher: CoroutineDispatcher,
) : CoroutineUseCase<SearchRequest, ArrayList<Project>>(coroutineDispatcher) {

    override suspend fun execute(parameter: SearchRequest): Result<ArrayList<Project>> {
        return projectRepository.searchByKeyword(parameter.auth, parameter.keyword)
    }
}

Next, use this usecase like this.

useCase.invoke(request)

And I want to check my mock repository worked. So I use mock verify and this failed.

verify(mockRepository).searchByKeyword(request.auth, request.keyword)

But another test below succeeded

mockRepository.searchByKeyword(request.auth, request.keyword)

verify(mockRepository).searchByKeyword(request.auth, request.keyword)

Should I call mock function directly?

Thank you for answer. and sorry for my English

All codes below

@ExperimentalCoroutinesApi
@Test
fun `check SearchProjectUseCase returns correct data`() = coroutineRule.runBlockingTest {

    val mockRepository = mock(ProjectRepository::class.java)

    val request = SearchRequest(
        "auth", "keyword"
    )

    `when`(mockRepository.searchByKeyword(request.auth, request.keyword)).thenReturn(projects)

    val useCase = SearchProjectsUseCase(
        mockRepository, coroutineRule.testDispatcher
    )

    //useCase.invoke(request) //failed

    mockRepository.searchByKeyword(request.auth, request.keyword) //succeeded

    verify(mockRepository).searchByKeyword(request.auth, request.keyword)
}
0

There are 0 best solutions below