我尝试测试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
}
}