I am trying to write a simple test for my MainPresenter(SchedulerProvider) class. It should check if the showEventFragment(String) and showPromptFragment(String) shows up after successful API response.
I create MainPresenter instance in MainActivity like this:
private val presenter: MainContract.Presenter = MainPresenter(AppSchedulerProvider())
Presenter class:
class MainPresenter(private val scheduler: SchedulerProvider) : MainContract.Presenter{
private val subscriptions = CompositeDisposable()
private val api: RxApiServiceInterface = RxApiServiceInterface.create()
private lateinit var view: MainContract.View
override fun subscribe() {
}
override fun unsubscribe() {
subscriptions.clear()
}
override fun loadProfileData() {
view.showLoadingView()
val subscribe = api.getProfileDataRequest()
.subscribeOn(scheduler.io())
.observeOn(scheduler.ui())
.subscribe({profileList : List<Profile> ->
view.showEventFragment(profileList[0].profile_id)
view.showPromptFragment(profileList[0].profile_id)
},{ error ->
view.showErrorMessage(error.message.toString())
view.showRetryView()
})
subscriptions.add(subscribe)
}
override fun attach(view: MainContract.View) {
this.view = view
}
}
Test class:
class MainPresenterTest {
#Mock
private lateinit var view: MainContract.View
private var api: RxApiServiceInterface = RxApiServiceInterface.create()
private lateinit var mainPresenter: MainPresenter
private lateinit var testScheduler: TestScheduler
private lateinit var testSchedulerProvider: TestSchedulerProvider
#Before
fun setup() {
MockitoAnnotations.initMocks(this)
testScheduler = TestScheduler()
testSchedulerProvider = TestSchedulerProvider(testScheduler)
mainPresenter = MainPresenter(testSchedulerProvider)
mainPresenter.attach(view)
}
#Test
fun getProfileSuccess() {
val address = Address("SillyStreet", "4", "80333", "NY")
val contact = Contact("i.am#dummy.com", "000 000 000 00")
val mockedProfile = Profile(
"freemium_profile",
"Dum",
"my",
"male",
"Sil ly",
true,
"First Class",
"1989-01-01",
address,
contact,
listOf("freemium", "signup_complete")
)
doReturn(Single.just(listOf(mockedProfile)))
.`when`(api)
.getProfileDataRequest()
mainPresenter.loadProfileData()
testSchedulerProvider.testScheduler.triggerActions()
verify(view).showLoadingView()
verify(view).showEventFragment(mockedProfile.profile_id)
verify(view).showPromptFragment(mockedProfile.profile_id)
}
}
RxApiServiceInterface interface:
interface RxApiServiceInterface {
#GET("user/customer/profiles")
fun getProfileDataRequest() : Single<List<Profile>>
companion object {
private val restClient by lazy {
RestClient.createRetrofit(API_URL)
}
fun create(): RxApiServiceInterface = restClient.create(RxApiServiceInterface::class.java)
}
}
TestSchedulerProvider class:
class TestSchedulerProvider constructor(val testScheduler: TestScheduler) : SchedulerProvider {
override fun ui(): Scheduler = testScheduler
override fun computation(): Scheduler = testScheduler
override fun io(): Scheduler = testScheduler
}
I am using these test libs:
testImplementation 'org.mockito:mockito-core:2.22.0'
testImplementation 'org.mockito:mockito-inline:2.22.0'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit:1.2.71'
androidTestImplementation 'org.mockito:mockito-android:2.7.22'
What the hell am I doing wrong, that I still get the "Wanted but not invoked error"?
The logs also says:
However, there was exactly 1 interaction with this mock:
view.showLoadingView();
but I am not suprised about that as this method is outside API query.
Related
I am testing my Repository class using Mockito, specifically getProducts() functionality:
class Repository private constructor(private val retrofitService: ApiService) {
companion object {
#Volatile
private var INSTANCE: Repository? = null
fun getInstance(retrofitService: ApiService): Repository {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Repository(retrofitService)
}
INSTANCE = instance
return instance
}
}
}
suspend fun getProducts(): ProductsResponse = withContext(IO) {
retrofitService.getProducts()
}
}
This is my test class:
#ExperimentalCoroutinesApi
#RunWith(MockitoJUnitRunner::class)
class RepositoryTest {
// Class under test
private lateinit var repository: Repository
// Executes each task synchronously using Architecture Components.
#get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
// Set the main coroutines dispatcher for unit testing.
#ExperimentalCoroutinesApi
#get:Rule
var mainCoroutineRule = MainCoroutineRule()
#Mock
private lateinit var retrofitService: ApiService
#Before
fun createRepository() {
MockitoAnnotations.initMocks(this)
repository = Repository.getInstance(retrofitService)
}
#Test
fun test() = runBlocking {
// GIVEN
Mockito.`when`(retrofitService.getProducts()).thenReturn(fakeProductsResponse)
// WHEN
val productResponse: ProductsResponse = repository.getProducts()
println("HERE = ${retrofitService.getProducts()}")
// THEN
println("HERE: $productResponse")
MatcherAssert.assertThat(productResponse, `is`(fakeProductsResponse))
}
}
And my ApiService:
interface ApiService {
#GET("https://www...")
suspend fun getProducts(): ProductsResponse
}
When I call repository.getProducts(), it returns null despite the fact, that I explicitly set retrofitService.getProducts() to return fakeProductsResponse, which is being called inside repository's getProducts() method. It should return fakeProductsResponse, but it returns null.
Am I doing wrong mocking or what the problem can be? Thanks...
EDIT: this is my MainCoroutineRule, if you need it
#ExperimentalCoroutinesApi
class MainCoroutineRule(val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()):
TestWatcher(),
TestCoroutineScope by TestCoroutineScope(dispatcher) {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
cleanupTestCoroutines()
Dispatchers.resetMain()
}
}
It might not be a complete solution to your problem, but what I see is that your MainCoroutineRule overrides the mainDispatcher Dispatchers.setMain(dispatcher).
But in
suspend fun getProducts(): ProductsResponse = withContext(IO)
you are explicitely setting an IO Dispatcher.
I recommend always setting the dispatcher from a property you pass via constructor:
class Repository private constructor(
private val retrofitService: ApiService,
private val dispatcher: CoroutineDispatcher) {
companion object {
fun getInstance(retrofitService: ApiService,
dispatcher: CoroutineDispatcher = Dispatchers.IO): Repository {
// ommit code for simplicity
instance = Repository(retrofitService, dispatcher)
// ...
}
}
}
suspend fun getProducts(): ProductsResponse = withContext(dispatcher) {
retrofitService.getProducts()
}
}
Having it a default parameter you do not need to pass it in your regular code, but you can exchange it within your unit test:
class RepositoryTest {
private lateinit var repository: Repository
#get:Rule
var mainCoroutineRule = MainCoroutineRule()
#Mock
private lateinit var retrofitService: ApiService
#Before
fun createRepository() {
MockitoAnnotations.initMocks(this)
repository = Repository.getInstance(retrofitService, mainCoroutineRule.dispatcher)
}
}
For my own unit tests I am using the blocking function of TestCoroutineDispatcher from the CoroutineRule like:
#Test
fun aTest() = mainCoroutineRule.dispatcher.runBlockingTest {
val acutal = classUnderTest.callToSuspendFunction()
// do assertions
}
I hope this will help you a bit.
MainActivity
class MainActivity : AppCompatActivity() {
#Inject
lateinit var mainViewModelFactory: mainViewModelFactory
private lateinit var mainActivityBinding: ActivityMainBinding
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityBinding = DataBindingUtil.setContentView(
this,
R.layout.activity_main
)
mainActivityBinding.rvmainRepos.adapter = mainAdapter
AndroidInjection.inject(this)
mainViewModel =
ViewModelProviders.of(
this#MainActivity,
mainViewModelFactory
)[mainViewModel::class.java]
mainActivityBinding.viewmodel = mainViewModel
mainActivityBinding.lifecycleOwner = this
mainViewModel.mainRepoReponse.observe(this, Observer<Response> {
repoList.clear()
it.success?.let { response ->
if (!response.isEmpty()) {
// mainViewModel.saveDataToDb(response)
// mainViewModel.createWorkerForClearingDb()
}
}
})
}
}
MainViewModelFactory
class MainViewModelFactory #Inject constructor(
val mainRepository: mainRepository
) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>) =
with(modelClass) {
when {
isAssignableFrom(mainViewModel::class.java) -> mainViewModel(
mainRepository = mainRepository
)
else -> throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}")
}
} as T
}
MainViewModel
class MainViewModel(
val mainRepository: mainRepository
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val mainRepoReponse = MutableLiveData<Response>()
val loadingProgress: MutableLiveData<Boolean> = MutableLiveData()
val _loadingProgress: LiveData<Boolean> = loadingProgress
val loadingFailed: MutableLiveData<Boolean> = MutableLiveData()
val _loadingFailed: LiveData<Boolean> = loadingFailed
var isConnected: Boolean = false
fun fetchmainRepos() {
if (isConnected) {
loadingProgress.value = true
compositeDisposable.add(
mainRepository.getmainRepos().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
run {
saveDataToDb(response)
)
}
},
{ error ->
processResponse(Response(AppConstants.Status.SUCCESS, null, error))
}
)
)
} else {
fetchFromLocal()
}
}
private fun saveDataToDb(response: List<mainRepo>) {
mainRepository.insertmainUsers(response)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(object : DisposableCompletableObserver() {
override fun onComplete() {
Log.d("Status", "Save Success")
}
override fun onError(e: Throwable) {
Log.d("Status", "error ${e.localizedMessage}")
}
})
}
}
MainRepository
interface MainRepository {
fun getmainRepos(): Single<List<mainRepo>>
fun getAllLocalRecords(): Single<List<mainRepo>>
fun insertmainUsers(repoList: List<mainRepo>): Completable
}
MainRepositoryImpl
class mainRepositoryImpl #Inject constructor(
val apiService: GitHubApi,
val mainDao: AppDao
) : MainRepository {
override fun getAllLocalRecords(): Single<List<mainRepo>> = mainDao.getAllRepos()
override fun insertmainUsers(repoList: List<mainRepo>) :Completable{
return mainDao.insertAllRepos(repoList)
}
override fun getmainRepos(): Single<List<mainRepo>> {
return apiService.getmainGits()
}
}
I'm quite confused with the implementation of MVVM with LiveData and Rxjava, in my MainViewModel I am calling the interface method and implementing it inside ViewModel, also on the response I'm saving the response to db. However, that is a private method, which won't be testable in unit testing in a proper way (because it's private). What is the best practice to call other methods on the completion of one method or i have to implement all the methods inside the implementation class which uses the interface.
Your ViewModel should not care how you are getting the data if you are trying to follow the clean architecture pattern. The logic for fetching the data from local or remote sources should be in the repository in the worst case where you can also save the response. In that case, since you have a contact for the methods, you can easily test them. Ideally, you could break it down even more - adding Usecases/Interactors.
I am using Junit & Mockito 4 for unit testing of viewModel.
ViewModel class
class MainViewModel(app: Application, private val githubRepo: GithubRepository) :
BaseViewModel(app) {
private val _trendingLiveData by lazy { MutableLiveData<Event<DataState<List<TrendingResponse>>>>() }
val trendingLiveData: LiveData<Event<DataState<List<TrendingResponse>>>> by lazy { _trendingLiveData }
var loadingState = MutableLiveData<Boolean>()
fun getTrendingData(language: String?, since: String?) {
launch {
loadingState.postValue(true)
when (val result = githubRepo.getTrendingListAsync(language, since).awaitAndGet()) {
is Result.Success -> {
loadingState.postValue(false)
result.body?.let {
Event(DataState.Success(it))
}.run(_trendingLiveData::postValue)
}
is Result.Failure -> {
loadingState.postValue(false)
}
}
}
}
}
Api EndPoinit
interface GithubRepository {
fun getTrendingListAsync(
language: String?,
since: String?
): Deferred<Response<List<TrendingResponse>>>
}
ViewModel Test class
#RunWith(JUnit4::class)
class MainViewModelTest {
#Rule
#JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
#Mock
lateinit var repo: GithubRepository
#Mock
lateinit var githubApi: GithubApi
#Mock
lateinit var application: TrendingApp
lateinit var viewModel: MainViewModel
#Mock
lateinit var dataObserver: Observer<Event<DataState<List<TrendingResponse>>>>
#Mock
lateinit var loadingObserver: Observer<Boolean>
private val threadContext = newSingleThreadContext("UI thread")
private val trendingList : List<TrendingResponse> = listOf()
#Before
fun setUp() {
MockitoAnnotations.initMocks(this)
Dispatchers.setMain(threadContext)
viewModel = MainViewModel(application, repo)
}
#Test
fun test_TrendingRepo_whenSuccess() {
//Assemble
Mockito.`when`(githubApi.getTrendingListAsync("java", "daily"))
.thenAnswer{ return#thenAnswer trendingList.toDeferred() }
//Act
viewModel.trendingLiveData.observeForever(dataObserver)
viewModel.loadingState.observeForever(loadingObserver)
viewModel.getTrendingData("java", "daily")
Thread.sleep(1000)
//Verify
verify(loadingObserver).onChanged(true)
//verify(dataObserver).onChanged(trendingList)
verify(loadingObserver).onChanged(false)
}
#After
fun tearDown() {
Dispatchers.resetMain()
threadContext.close()
}
}
Problem is that my livedata is wrapped around Event<DataState<List<TrendingResponse>>, due to which I am not able to get what should be dataObserver and how should I verify that dataObserver in the test class.
Event os open class that is to handle event like SingleLiveData
DataState is sealed class that contain SUCCESS & FAILED data class
I have written test case livedata is like LiveData<List<Response> or something like that.
You need to wrap the List<TrendingResponse> → Event(DataState.Success(List<TrendingResponse>)) which you are returning using mockito - trendingList.toDeferred().
#Test
fun test_TrendingRepo_whenSuccess() {
//Assemble
Mockito.`when`(githubApi.getTrendingListAsync("java", "daily"))
.thenAnswer{ return#thenAnswer trendingList.toDeferred() }
//Act
viewModel.trendingLiveData.observeForever(dataObserver)
viewModel.loadingState.observeForever(loadingObserver)
viewModel.getTrendingData("java", "daily")
Thread.sleep(1000)
//Verify
verify(loadingObserver).onChanged(true)
//wrap the trendingList inside Event(DataState(YourList))
verify(dataObserver).onChanged(Event(DataState.Success(trendingList)))
verify(loadingObserver).onChanged(false)
}
I am trying to mock a response from my usecases, this usecase works with coroutines.
fun getData() {
view?.showLoading()
getProductsUseCase.execute(this::onSuccessApi, this::onErrorApi)
}
My useCase is injected on presenter.
GetProductsUseCase has this code:
class GetProductsUseCase (private var productsRepository: ProductsRepository) : UseCase<MutableMap<String, Product>>() {
override suspend fun executeUseCase(): MutableMap<String, Product> {
val products =productsRepository.getProductsFromApi()
return products
}
}
My BaseUseCase
abstract class UseCase<T> {
abstract suspend fun executeUseCase(): Any
fun execute(
onSuccess: (T) -> Unit,
genericError: () -> Unit) {
GlobalScope.launch {
val result = async {
try {
executeUseCase()
} catch (e: Exception) {
GenericError()
}
}
GlobalScope.launch(Dispatchers.Main) {
when {
result.await() is GenericError -> genericError()
else -> onSuccess(result.await() as T)
}
}
}
}
}
This useCase call my repository:
override suspend fun getProductsFromApi(): MutableMap<String, Product> {
val productsResponse = safeApiCall(
call = {apiService.getProductsList()},
error = "Error fetching products"
)
productsResponse?.let {
return productsMapper.fromResponseToDomain(it)!!
}
return mutableMapOf()
}
Y try to mock my response but test always fails.
#RunWith(MockitoJUnitRunner::class)
class HomePresenterTest {
lateinit var presenter: HomePresenter
#Mock
lateinit var view: HomeView
#Mock
lateinit var getProductsUseCase: GetProductsUseCase
#Mock
lateinit var updateProductsUseCase: UpdateProductsUseCase
private lateinit var products: MutableMap<String, Product>
private val testDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(testDispatcher)
#Mock
lateinit var productsRepository:ProductsRepositoryImpl
#Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
products = ProductsMotherObject.createEmptyModel()
presenter = HomePresenter(view, getProductsUseCase, updateProductsUseCase, products)
}
#After
fun after() {
Dispatchers.resetMain()
testScope.cleanupTestCoroutines()
}
//...
#Test
fun a() = testScope.runBlockingTest {
setTasksNotAvailable(productsRepository)
presenter.getDataFromApi()
verify(view).setUpRecyclerView(products.values.toMutableList())
}
private suspend fun setTasksNotAvailable(dataSource: ProductsRepository) {
`when`(dataSource.getProductsFromApi()).thenReturn((mutableMapOf()))
}
}
I don't know what is happening. The log says:
"Wanted but not invoked:
view.setUpRecyclerView([]);
-> at com.myProject.HomePresenterTest$a$1.invokeSuspend(HomePresenterTest.kt:165)
However, there was exactly 1 interaction with this mock:
view.showLoading();"
The problem is with how you create your GetProductsUseCase.
You're not creating it with the mocked version of your ProductsRepository, yet you're mocking the ProductsRepository calls.
Try to create the GetProductsUseCase manually and not using a #Mock
// no #Mock
lateinit var getProductsUseCase: GetProductsUseCase
#Before
fun setUp() {
// ...
// after your mocks are initialized...
getProductsUseCase = GetProductsUseCase(productsRepository) //<- this uses mocked ProductsRepository
}
I am trying to test RxJava2's "debounce" operator in the Android.
I used the "debounce" operator for the search feature.
In the View(Activity), searching is started.
etSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable) {
mPresenter.search(editable.toString())
}
...
})
And the Presenter is here:
class MyPresenter(
private val view: MyContract.View,
private val apiService: ApiServie = ApiServiceImpl(),
private val searchSubject: PublishSubject<String> = PublishSubject.create(),
var debounceScheduler: Scheduler = Schedulers.computation()
) : MyContract.Presenter {
init {
setupSearch()
}
override fun search(keyword: String) {
if (searchDisposable.size() == 0) {
setupSearch()
}
searchSubject.onNext(keyword)
}
private fun setupSearch() {
searchSubject.debounce(1000, TimeUnit.MILLISECONDS, debounceScheduler)
.distinctUntilChanged()
.switchMap { keyword ->
apiService.search(keyword)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { response ->
response.data?.let { data ->
view.searchResult(data)
}
}
}
}
Actually, it works fine when I do the integration test.
But what I want to do is testing the "search" function of the MyPresenter class.
To do this, I read an article
But it doesn't work...
My test code is here:
class MyTest {
#Mock
private lateinit var mockView: MyContract.View
#Mock
private lateinit var mockApiService: ApiService
private lateinit var mMyPresenter: MyPresenter
private lateinit var inOrder: InOrder
private val mTestScheduler: TestScheduler = TestScheduler()
private val ZERO = 0
private fun setUpScheduler() {
val immediate = object : Scheduler() {
override fun createWorker() = ExecutorScheduler.ExecutorWorker(Runnable::run)
}
RxJavaPlugins.setInitIoSchedulerHandler { immediate }
RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediate }
}
#Before
fun setup() {
MockitoAnnotations.initMocks(this)
setUpScheduler()
mMyPresenter = MyPresenter(mockView, mockApiService)
inOrder = inOrder(mockView)
}
#Test
fun searchBillsTest() {
`when`(mockApiService.search("America"))
.thenReturn(Observable.just(mockResult))
mMyPresenter.debounceScheduler = mTestScheduler
mMyPresenter.search("America")
mTestScheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS)
verify(mockView).searchResult(mockResult)
}
}
The last verify is not called...
I don't know why...
I added "doOnNext" to print log to find the cause in "searchSubject", but "doOnNext" is not called...
"doOnSubscribe" is called...
Please do you know why?
In order to as quick as pass your test code just change few things.
Use TestScheduler
Divide ui and io scheduler.
Use Scheduler.triggerActions before trigger events for subject.
#RunWith(MockitoJUnitRunner::class)
class DebounceTest {
private lateinit var searchSubject: PublishSubject<String>
#Mock lateinit var apiService: ApiService
#Mock lateinit var presenter: Presenter
private lateinit var disposable: Disposable
private lateinit var ioTestScheduler: TestScheduler
private lateinit var uiTestScheduler: TestScheduler
#Before fun setUp() {
searchSubject = PublishSubject.create<String>()
ioTestScheduler = TestScheduler()
uiTestScheduler = TestScheduler()
setupSearch(uiTestScheduler, ioTestScheduler)
// important https://stackoverflow.com/a/53543257/1355048
ioTestScheduler.triggerActions()
}
#After fun tearDown() {
disposable.dispose()
}
#Test fun searchBillsTest() {
`when`(apiService.search("America")).thenReturn(Observable.just("MOCK RESULT"))
searchSubject.onNext("America")
ioTestScheduler.advanceTimeBy(1, TimeUnit.SECONDS)
uiTestScheduler.triggerActions()
verify(presenter).doSomething("MOCK RESULT")
}
private fun setupSearch(uiScheduler: Scheduler, ioScheduler: Scheduler) {
disposable = searchSubject.debounce(1, TimeUnit.SECONDS, ioScheduler)
.distinctUntilChanged()
.switchMap { apiService.search(it) }
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
.subscribe { response ->
presenter.doSomething(response)
}
}
interface ApiService {
fun search(query: String): Observable<String>
}
interface Presenter {
fun doSomething(result: String)
}
}