android 使用Mockito和FirebaseKotlin进行单元测试

sqserrrh  于 2023-09-28  发布在  Android
关注(0)|答案(1)|浏览(117)

我正在尝试为我的Kotlin类编写一个单元测试,它可以从Firebase写入和读取值。我尝试了不同的方法来编写测试,但总是在firebase上出错。这是我的Repository类:

package mainPackage.model

import com.google.firebase.firestore.FirebaseFirestore
import android.util.Log
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.utils.Checks

const val TAG = "FIRESTORE"

class RepositoryMockup {

    //--------------------------------

//Firebase functions

fun writeNewUser(pass: String, email: String, isATeacher: Boolean?) {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection("Users").document(email)

    val newUser = hashMapOf(
        "is_a_teacher" to isATeacher,
        "pass" to pass
    )

    myRef.set(newUser)
        .addOnSuccessListener { Log.d(TAG, "User successfully added") }
        .addOnFailureListener { e -> Log.w(TAG, "Error writing user", e) }

}

//CHECKED AND FIXED

fun userLogin(user: User, callback: (Checks) -> Unit) {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection("Users").document(user.email.toString())
    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null && document.exists()) {
                val pass = document.get("pass") as String
                if (pass == user.password) {
                    callback(Checks.PASSED)
                } else {
                    callback(Checks.FAILED_CHECK)
                }
                Log.d(TAG, "Pass successfully checked")
            } else {
                callback(Checks.NEW_USER_CREATED)
                Log.d(TAG, "Is empty")
                writeNewUser(user.password.toString(), user.email.toString(), user.isATeacher)
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
            callback(Checks.FAILED_CHECK)
        }
}

fun userLoginTest(user: UserTest, callback: (Checks) -> Unit) {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection("Users").document(user.email.toString())
    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null && document.exists()) {
                val pass = document.get("pass") as String
                if (pass == user.pass) {
                    callback(Checks.PASSED)
                } else {
                    callback(Checks.FAILED_CHECK)
                }
                Log.d(TAG, "Pass successfully checked")
            } else {
                callback(Checks.NEW_USER_CREATED)
                Log.d(TAG, "Is empty")
                writeNewUser(user.pass.toString(), user.email.toString(), user.isATeacher)
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
            callback(Checks.FAILED_CHECK)
        }
}



//CHECKED AND FIXED

fun readNameSurnameByEmail(email: String, callback: (String) -> Unit){
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection("Users").document(email)

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                val fieldValue = document.get("name_surname") as String
                callback(fieldValue)
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
}

//CHECKED

fun readIsATeacherByEmail(email: String): Boolean {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection("Users").document(email)
    var fieldValue = false

    myRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                fieldValue = document.get("is_a_teacher") as Boolean
                Log.d(TAG, "Name and surname successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
    return fieldValue
}

//CHECKED

fun writeOfficeHoursInstance(email: String, timeFrom: String, timeTo: String) {
    val database = FirebaseFirestore.getInstance()
    var id = ""
    val myRef = database.collection("OfficeHoursInstance").document()
    id = myRef.id
    val newInstance = hashMapOf(
        "email" to email,
        "time_from" to timeFrom,
        "time_to" to timeTo,
        "id" to id
    )

    myRef.set(newInstance)
        .addOnSuccessListener { Log.d(TAG, "Instance successfully added") }
        .addOnFailureListener { e -> Log.w(TAG, "Error writing Instance", e) }


}

//CHECKED AND FIXED

fun readOfficeHoursInstanceTeacher(email: String, callback: (MutableList<OfficeHoursInstance>) -> Unit){
    var timeFrom = ""
    var timeTo = ""
    var userEmail = ""
    var code = ""
    var list = mutableListOf<OfficeHoursInstance>()
    val database = FirebaseFirestore.getInstance()
    val ref = database.collection("OfficeHoursInstance")
        .whereEqualTo("email", email)
    ref.get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                timeFrom = document.get("time_from") as String
                timeTo = document.get("time_to") as String
                userEmail = document.get("email") as String
                code = document.get("id") as String
                list.add(OfficeHoursInstance(userEmail, timeFrom, timeTo, code))
                Log.d(TAG, " Time instance successfully read")
            }
            callback(list)
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
}

fun updateUserOfficeHoursList(email: String, code: String){
    val database = FirebaseFirestore.getInstance()
    val ref = database.collection("Users").document(email)
    var list = ""

    ref.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                list = document.get("office_hours_list") as String
                Log.d(TAG, "office_hours_list successfully read")
            } else {
                Log.d(TAG, "Is empty")
            }
        }
        .addOnFailureListener { exception ->
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, "Error getting document: ", exception)
            }
        }
    if (list.isEmpty()){
        list = code
    }
    else {
        list + ", " + code
    }
    ref.update("office_hours_list", list)
}

}
你能给予我一个提示如何为我的数据库方法写一个单元测试吗?或者让我看看结构?
这是我的,但它不工作:

package mainPackage.tests

import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.model.RepositoryMockup
import mainPackage.model.UserTest
import mainPackage.utils.Checks
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations

class RepositoryMockupTest {

    private lateinit var repositoryMockup: RepositoryMockup

    @Mock
    private lateinit var firebaseFirestore: FirebaseFirestore

    @Mock
    private lateinit var documentSnapshot: DocumentSnapshot

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        repositoryMockup = RepositoryMockup()
    }

    @Test
    fun testWriteNewUser() {
        repositoryMockup.writeNewUser("password", "email", true)
        Mockito.verify(firebaseFirestore).collection("Users").document("email")
    }

    @Test
    fun testUserLogin_Passed() {
        val user = UserTest("[email protected]", "password123", true)
        Mockito.`when`(firebaseFirestore.collection("Users").document("email").get())
            .thenReturn(documentSnapshot)
        Mockito.`when`(documentSnapshot.exists()).thenReturn(true)
        Mockito.`when`(documentSnapshot.get("pass")).thenReturn("password")
        var check = Checks.FAILED_CHECK
        repositoryMockup.userLoginTest(user) {
            check = it
        }
        assertEquals(Checks.PASSED, check)
    }

    @Test
    fun testUserLogin_FailedCheck() {
        val user = UserTest("[email protected]", "wrong_password", true)
        Mockito.`when`(firebaseFirestore.collection("Users").document("user.email").get())
            .thenReturn(documentSnapshot)
        Mockito.`when`(documentSnapshot.exists()).thenReturn(true)
        Mockito.`when`(documentSnapshot.get("pass")).thenReturn("password")
        var check = Checks.PASSED
        repositoryMockup.userLoginTest(user) {
            check = it
        }
        assertEquals(Checks.FAILED_CHECK, check)
    }

//    @Test
//    fun testUserLogin_NewUserCreated() {
//        val user = UserTest("email", "password", true)
//        Mockito.`when`(firebaseFirestore.collection("Users").document("user.email").get())
//            .thenReturn(documentSnapshot)
//        Mockito.`when`(documentSnapshot.exists()).thenReturn(false)
//        var check = Checks.PASSED
//        repositoryMockup.userLoginTest(user) {
//            check = it
//        }
//        assertEquals(Checks.NEW_USER_CREATED, check)
//    }
}

private fun Any.thenReturn(documentSnapshot: DocumentSnapshot) {

}
arknldoa

arknldoa1#

你可以试试这个:

// Optional -- Robolectric environment
   const val coreTest = "androidx.test:core:1.5.0"
   // Optional -- Mockito framework
   const val mockito = "org.mockito:mockito-core:5.5.0"
   // Optional -- mockito-kotlin
   const val mockitoKotlin = "org.mockito.kotlin:mockito-kotlin:5.1.0"
   // Optional -- Mockk framework
   const val mockk = "io.mockk:mockk:v1.13.8"

添加上述库。
编码:FileTest.kt

@Before
    fun setup() {
        MockitoAnnotations.openMocks(FileTest::class)
    }

    @Test
    fun getAllUsersFromFirebase() = runBlocking {
        val getRepositoryUseCase = mock(Repository::class.java)

        `when`(getRepositoryUseCase.invoke()).thenReturn(listData())
        val response = getRepositoryUseCase.invoke()

        Assert.assertTrue(response == listUserDummy())
    }

相关问题