How do I fake a Firestore Flow<QuerySnapshot> in Kotlin - android

I am trying to test my app with firestore and I don't know how will I fake the datasource with a Flow to test my repository. I'm trying to follow the pattern from google codelabs but I only convert toObject in the composable. How can I write the repository test?
below is my FirestoreDatasource and my Repository and the FakeDatasource I am trying to write
#Singleton
class FirestoreDatasourceImpl #Inject constructor(
private val firestore: FirebaseFirestore
) : FirestoreDatasource {
override suspend fun addUser(user: UserModel) {
firestore.collection(USERS)
.document(user.id)
.set(user, SetOptions.merge())
}
#ExperimentalCoroutinesApi
override fun getAllUsers(userId: String) = callbackFlow {
val collection = firestore.collection(USERS).whereNotEqualTo("id", userId)
val snapshotListener = collection.addSnapshotListener() { snapshot, e ->
this.trySend(snapshot).isSuccess
}
awaitClose {
snapshotListener.remove()
}
}
}
#Singleton
class FirestoreRepositoryImpl #Inject constructor(
private val firestoreClass: FirestoreDatasourceImpl
) : FirestoreRepository{
override suspend fun addUser(user: UserModel){
firestoreClass.addUser(user)
}
#ExperimentalCoroutinesApi
override fun getAllUsers(userId: String) : Flow<QuerySnapshot?> {
return firestoreClass.getAllUsers(userId)
}
}
internal class FakeFirestoreDatasourceImplTest constructor(
private var userList: MutableList<UserModel>? = mutableListOf()
) : FirestoreDatasource{
override suspend fun addUser(user: UserModel) {
userList?.add(user)
}
override fun getAllUsers(userId: String): Flow<QuerySnapshot?> {
}
}

Related

Unit Testing in Android

I am trying to unit test my repository . In that i want to write test for function which makes api calls.(function name :- searchImage)
The function calls datasource for actual api calls.
I am using a fake data source which extends from the shopping data source interface.
How can i provide different responses from fake data source for the api calls like no internet , Null body or Success response.
ShoppingRepositoryInterface
interface ShoppingRepository {
suspend fun insertShoppingItem(shoppingItem: ShoppingItem)
suspend fun deleteShoppingItem(shoppingItem: ShoppingItem)
fun getAllShoppingItems() : LiveData<List<ShoppingItem>>
fun getTotalPrice() : LiveData<Float>
suspend fun searchImage(q:String) : Resource<ImageResponse>
}
ShoppingRepositoryImpl
#ViewModelScoped
class ShoppingRepositoryImpl #Inject constructor(
private val dataSource: ShoppingDataSource
) : ShoppingRepository{
override suspend fun insertShoppingItem(shoppingItem: ShoppingItem) = dataSource.insertShoppingItem(shoppingItem)
override suspend fun deleteShoppingItem(shoppingItem: ShoppingItem) = dataSource.deleteShoppingItem(shoppingItem)
override fun getAllShoppingItems() = dataSource.getAllShoppingItems()
override fun getTotalPrice() = dataSource.getTotalPrice()
override suspend fun searchImage(q: String) : Resource<ImageResponse> {
return try {
val response = dataSource.searchImage(q)
if(response.isSuccessful){
response.body()?.let {
Resource.Success(it)
}?:Resource.Error("Some Error Occurred")
}else{
Resource.Error("Some Error Occurred")
}
}catch (e:Exception){
Resource.Error("Couldn't connect to the server.Please try later")
}
}
}
ShoppingReposositoryTest
class ShoppingRepositoryTest{
#get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var repository: ShoppingRepository
private lateinit var dataSource: ShoppingDataSource
private val shoppingItem1 = ShoppingItem("name1",1,price=1f,"url1",1)
private val shoppingItem2 = ShoppingItem("name2",2,price=2f,"url2",2)
private val shoppingItem3 = ShoppingItem("name3",3,price=3f,"url3",3)
#Before
fun setup(){
dataSource = FakeDataSource(mutableListOf(
shoppingItem1
))
repository = ShoppingRepositoryImpl(dataSource)
}
#Test
#ExperimentalCoroutinesApi
fun insertShoppingItem_returnsWhetherItemInserted() = runTest{
//Given
//When
repository.insertShoppingItem(shoppingItem2)
val shoppingList = repository.getAllShoppingItems().getOrAwaitValue()
//Then
assertThat(shoppingList).contains(shoppingItem1)
}
#Test
#ExperimentalCoroutinesApi
fun deleteShoppingItem_returnsWhetherItemDeleted() = runTest{
//Given
//When
repository.deleteShoppingItem(shoppingItem1)
val shoppingList = repository.getAllShoppingItems().getOrAwaitValue()
//Then
assertThat(shoppingList.contains(shoppingItem1)).isFalse()
}
#Test
#ExperimentalCoroutinesApi
fun observeTotalPrice_returnsTotalPrice() = runTest {
//Given
//When
repository.insertShoppingItem(shoppingItem2)
repository.insertShoppingItem(shoppingItem3)
val actual = repository.getTotalPrice().getOrAwaitValue()
val expected = 14f
//Then
assertThat(expected).isEqualTo(actual)
}
#Test
#ExperimentalCoroutinesApi
fun observesSearchImage_returnsNoInternetError() = runTest {
//Given
//When
}
ShoppingDataSourceInterface
interface ShoppingDataSource {
suspend fun insertShoppingItem(shoppingItem:ShoppingItem)
suspend fun deleteShoppingItem(shoppingItem: ShoppingItem)
fun getAllShoppingItems() : LiveData<List<ShoppingItem>>
fun getTotalPrice() : LiveData<Float>
suspend fun searchImage(q:String) : Response<ImageResponse>
}
FakeDataDource
class FakeDataSource(private val list: MutableList<ShoppingItem> = mutableListOf()) : ShoppingDataSource {
private val shoppingList = MutableLiveData<List<ShoppingItem>>()
get() {
field.value=list
return field
}
private val totalPrice = MutableLiveData<Float>()
get(){
var value=0f
for(item in shoppingList.value!!){
value+=(item.price*item.amount)
}
field.value=value
return field
}
override suspend fun insertShoppingItem(shoppingItem: ShoppingItem) {
list.add(shoppingItem)
}
override suspend fun deleteShoppingItem(shoppingItem: ShoppingItem) {
list.remove(shoppingItem)
}
override fun getAllShoppingItems(): LiveData<List<ShoppingItem>> = shoppingList
override fun getTotalPrice(): LiveData<Float> {
return totalPrice
}
override suspend fun searchImage(q: String): Response<ImageResponse> {
TODO("")
}
I cannot use some booleans etc since it extends ShoppingDataSource Interface .
I tried mocking as well but that didn't work . What should be done now?

How can i get one item from Room database?

So, I have two ViewModels and two screens in my app. The first screen is for the presentation of a list of diary item elements, second is for detailed information on diary items. In a second ViewModel, I have an id to get a record from DB but can find it. What can I do to get it?
DAO:
interface DiaryDao {
#Query("SELECT * FROM diaryItems")
fun getAllDiaryPosts(): LiveData<List<DiaryItem>>
#Query("Select * from diaryItems where id = :id")
fun getDiaryPostById(id: Int) : DiaryItem
#Query("Delete from diaryItems where id = :index")
fun deleteDiaryPostByIndex(index : Int)
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertDiaryPost(diaryItem: DiaryItem)
#Update
suspend fun updateDiaryPost(diaryItem: DiaryItem)
#Delete
suspend fun deleteDiaryPost(diaryItem: DiaryItem)
#Query("Delete from diaryItems")
suspend fun deleteAllDiaryItems()
}
Repository
class DiaryRepository #Inject constructor(private val diaryDao: DiaryDao) {
val readAllData: LiveData<List<DiaryItem>> = diaryDao.getAllDiaryPosts()
suspend fun getDiaryPostDyIndex(index: Int): DiaryItem {
return diaryDao.getDiaryPostById(index)
}
}
First viewmodel
#HiltViewModel
class PostListViewModel
#Inject
constructor(
private val diaryRepository: DiaryRepository,
) : ViewModel() {
private var allDiaryItems: LiveData<List<DiaryItem>> = diaryRepository.readAllData
}
Second viewmodel
#HiltViewModel
class PostDetailViewModel
#Inject
constructor(
private val savedStateHandle: SavedStateHandle,
private val diaryRepository: DiaryRepository
) : ViewModel() {
sealed class UIState {
object Loading: UIState()
data class Success(val currentPosts: DiaryItem) : UIState()
object Error : UIState()
}
val postDetailState: State<UIState>
get() = _postDetailState
private val _postDetailState = mutableStateOf<UIState>(UIState.Loading)
init {
viewModelScope.launch (Dispatchers.IO) {
try {
val diaryList: DiaryItem = diaryRepository.getDiaryPostDyIndex(2) //it is for test
_postDetailState.value = UIState.Success(diaryList)
} catch (e: Exception) {
withContext(Dispatchers.Main) {
_postDetailState.value = UIState.Error
}
}
}
}
}
I am sure you are getting errors. because you updating UI State in IO Thread
fun getDairyItem(itemId: Int){
viewModelScope.launch (Dispatchers.IO) {
try {
val diaryList: DiaryItem = diaryRepository.getDiaryPostDyIndex(itemId)
withContext(Dispatchers.Main) {
_postDetailState.value = UIState.Success(diaryList)
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
_postDetailState.value = UIState.Error
}
}
}
}

Save remote data separately related tables when using NetworkBoundRepository with coroutines (android)

I want to use Single source of truth principle in my application. How can I add multiple table when using NetworkBoundRepository.
MainApi.kt
interface MainApi {
#GET("main")
suspend fun getMain(): Response<MainResponse>
}
MainResponse.kt
#JsonClass(generateAdapter = true)
data class MainResponse(
#Json(name = "categories") val categoryList: List<Category>,
#Json(name = "locations") val locationList: List<Location>,
#Json(name = "tags") val tagList: List<Tag>
)
NetworkBoundRepository.kt
#ExperimentalCoroutinesApi
abstract class NetworkBoundRepository<RESULT, REQUEST> {
fun asFlow() = flow<Resource<RESULT>> {
emit(Resource.Success(fetchFromLocal().first()))
val apiResponse = fetchFromRemote()
val remoteCategories = apiResponse.body()
if (apiResponse.isSuccessful && remoteCategories != null) {
saveRemoteData(remoteCategories)
} else {
emit(Resource.Failed(apiResponse.message()))
}
emitAll(
fetchFromLocal().map {
Resource.Success<RESULT>(it)
}
)
}.catch { e ->
emit(Resource.Failed("Network error! Can't get latest categories."))
}
#WorkerThread
protected abstract suspend fun saveRemoteData(response: REQUEST)
#MainThread
protected abstract fun fetchFromLocal(): Flow<RESULT>
#MainThread
protected abstract suspend fun fetchFromRemote(): Response<REQUEST>
}
MainRepository.kt
#ExperimentalCoroutinesApi
class MainRepository #Inject constructor(
private val mainApi: MainApi,
private val categoryDao: CategoryDao,
private val locationDao: LocationDao,
private val tagDao: TagDao
) {
suspend fun getMain(): Flow<Resource<List<Category>>> {
return object : NetworkBoundRepository<List<Category>, List<Category>>() {
override suspend fun saveRemoteData(response: List<Category>) = categoryDao.insertList(response)
override fun fetchFromLocal(): Flow<List<Category>> = categoryDao.getList()
override suspend fun fetchFromRemote(): Response<List<Category>> = mainApi.getMain()
}.asFlow()
}
}
Currently NetworkBoundRepository and MainRepository only works with categories. I want to fetch some data from internet and save each data to related tables in database. App must be offline first.
How can I add locationDao, tagDao to MainRepository?
I don't quite follow your question. You are adding locationDao and tagDao to MainRepository already here:
class MainRepository #Inject constructor(
...
private val locationDao: LocationDao,
private val tagDao: TagDao
)
If you are asking how to provide them in order for them to injectable via Dagger2 you have to either define dao constructor as #Inject or add #Provides or #Binds annotated methods with the relevant return type to the needed #Module, and tangle them in the same #Scope - more here
If you asking how to use those repos in your functions it is also easy:
object : NetworkBoundRepository<List<Category>, MainResponse>() {
override suspend fun saveRemoteData(response: MainResponse) = response?.run{
categoryDao.insertList(categoryList)
locationDao.insertList(locationList)
tagDao.insertList(tagList)
}
override fun fetchCategoriesFromLocal(): Flow<List<Category>> = categoryDao.getList()
override fun fetchLocationsFromLocal(): Flow<List<Location>> = locationDao.getList()
override fun fetchTagsFromLocal(): Flow<List<Tag>> = tagDao.getList()
override suspend fun fetchFromRemote(): Response<MainResponse> = mainApi.getMain()
//This function is not tested and written more like a pseudocode
override suspend fun mapFromLocalToResponse(): Flow<MainResponse> = fetchCategoriesFromLocal().combine(fetchLocationsFromLocal(), fetchTagsFromLocal()){categories, locations, tags ->
MainResponse(categories,locations,tags)
}
}
Maybe some more adjustments will be needed. But the main problem of your code is that you are trying to combine all the different entities into one repo and it is not very good(and the request that returns all the stuff under one response is not good either) - I would suggest to split it somehow not to mix it all.

Correct structure of implementing MVVM LiveData RxJava Dagger Databinding?

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.

How to inject data source factory from android pagination library?

I'm using pagination library and i want to inject datasource into my viewmodel.
My factory looks like:
class ArticleDataSourceFactory #Inject constructor(
val articleRepository: ArticleRepository
) : DataSource.Factory<Long, Article>() {
override fun create(): DataSource<Long, Article> {
return ArticleDateKeyedDataSource(articleRepository)
}
}
My DataSource:
class ArticleDateKeyedDataSource(
private val repository: ArticleRepository
) : ItemKeyedDataSource<Long, Article>() {
override fun loadInitial(params: LoadInitialParams<Long>, callback: LoadInitialCallback<Article>) {
val articles = repository.getInitial(params.requestedInitialKey!!, params.requestedLoadSize)
callback.onResult(articles)
}
override fun loadAfter(params: LoadParams<Long>, callback: LoadCallback<Article>) {
val articles = repository.getAfter(params.key, params.requestedLoadSize)
callback.onResult(articles)
}
override fun loadBefore(params: LoadParams<Long>, callback: LoadCallback<Article>) {
val articles = repository.getBefore(params.key, params.requestedLoadSize)
callback.onResult(articles)
}
override fun getKey(item: Article): Long {
return item.createdAt
}
}
And my ViewModel:
class ArticleFragmentViewModel #Inject constructor(
private val dataSourceFactory: ArticleDataSourceFactory
) : BaseViewModel() {
var initialArticlePosition = 0L
val navigateToArticleDetails: MutableLiveData<SingleEvent<Long>> = MutableLiveData()
val articlesLiveList: LiveData<PagedList<Article>>
get() {
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(5)
.build()
return LivePagedListBuilder(dataSourceFactory, config)
.setInitialLoadKey(initialArticlePosition)
.setFetchExecutor(Executors.newSingleThreadExecutor())
.build()
}
fun onArticleSelected(createdAt: Long) {
navigateToArticleDetails.value = SingleEvent(createdAt)
}
}
After rebuild, i get an error:
error: cannot access DataSource
class file for androidx.paging.DataSource not found
Consult the following stack trace for details.
What does it mean? I have no idea, what i do wrong.
For example, i have no problem to inject repository.
Did you use Android Module? You may need to use api dependency in the base module like
api "androidx.paging:paging-runtime-ktx:$paging_version"
And there is similar issue https://stackoverflow.com/a/47128596/5934119

Categories

Resources