我如何测试Firestore?

时间:2019-07-28 10:13:00

标签: android unit-testing kotlin google-cloud-firestore mockito

我尝试测试userService。为此,我通过构造函数用FirebaseFirestore准备了模拟userService和普通对象firebaseFirestore。当我运行测试时,我的对象firebaseFirestore的每个字段都为null。据我所知,我不能在测试FirebaseFirestore.getInstance()中使用。我该如何测试?

@LargeTest
class UserServiceTest {

@Mock
private lateinit var firebaseFirestore: FirebaseFirestore
private lateinit var userService: UserService

constructor() {
    MockitoAnnotations.initMocks(this)
    userService = UserService(firebaseFirestore)
}

@Test
fun getUserByLogin() {
    Mockito.`when`(userService.getUserById("id", 1)).thenReturn(User())
}

}

class UserService {

 private val DATABASE_BANKOK: FirebaseFirestore 

 constructor(databaseInstance: FirebaseFirestore) {
    DATABASE_BANKOK = databaseInstance
 }

 fun getUserByLogin(fieldName: String, login: String): User {
    var user = User()
    DATABASE_BANKOK.collection(COLLECTION_NAME)
        .whereEqualTo(fieldName, login)
        .get()
        .addOnSuccessListener { result ->
            if (result.isEmpty) {
                Log.i(TAG, "User doesn't exist")
            }
            for (document in result) {
                user = document.toObject(User::class.java)
                Log.i(TAG, "Result from database: {$user}")
            }
        }
        .addOnFailureListener { exception ->
            Log.e(TAG, "Error getting documents. Details: /n 
        {${exception.stackTrace}")
        }
    return user
}

}

0 个答案:

没有答案