简体   繁体   中英

How to run unit tests on Android Firebase Kotlin?

So I am building a chat App using Firebase Backend. Before implementing ViewModel and the actual fragment, I want to check whether my Firebase Repository works or not. My call to get the users will go like this

Fragmet -> ViewModel -> Repository -> FirebaseRepository -> suspend fun getAllUsers(): ArrayList

The code is:

class Repository(val firebaseRepository : FirebaseRepository) {

    suspend fun getAllUsersFromFirebase() : ArrayList<UserInfo> {
        return firebaseRepository.getAllUsers()
    }

}

class FirebaseRepository() {

    private val TAG = "FIREBASE REPOSITORY : "

    private val firebaseAuth:FirebaseAuth = FirebaseAuth.getInstance()
    private val firebaseDatabase :FirebaseDatabase = FirebaseDatabase.getInstance()

    suspend fun getAllUsers() : ArrayList<UserInfo> {
        val ref = firebaseDatabase.getReference("/users")
        val userList = ArrayList<UserInfo>()

        ref.addListenerForSingleValueEvent(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if(snapshot.exists()) {
                    Log.d(TAG,"$snapshot")
                    val tempList = ArrayList<UserInfo>()
                    for(child in snapshot.children){
                        val temp = child.getValue(UserInfo::class.java)
                        if(!temp?.userId!!.equals(firebaseAuth.currentUser!!.uid)) {
                            tempList.add(temp)
                        }
                    }
                }
            }

            override fun onCancelled(error: DatabaseError) {
                Log.d(TAG,"$error ${error.message}")
            }

        })

        if(userList.isEmpty()) {
            userList.add(UserInfo("NO USER FOUND","NO USER FOUND","NO USER FOUND","NO USER FOUND"))
        }

        return userList
    }
}

So how do I test this? I surmise that firebaseAuth may pose a problem. I think I can deal with it but how do I test this firebase call?

I want to check whether my firebase Repository works or not.

It won't work because you are returning the userList as a result of a method, which is actually not possible since the Firebase API is asynchronous. So the issue here is that the listener you have attached is being invoked some unknown amount of time after the query finishes and you'll never know how long it's going to take. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available.

That being said, your userList will be empty until the callback is invoked. This means that you should always use the results from within the callback. I have written an article regarding this topic called that will help you understand the concept:

If you want to create a unit test, then I recommend you use mockito and use the answer the answer from the following post:

PS Your getAllUsers() method doesn't need to be a suspend fun, because you aren't using any await() there. If you want to use that, I recommend you read the following article:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM