我正在为我的应用编写单元测试。我需要测试一个处理我的应用程序内部登录的函数。此登录处理程序使用回调,在登录完成时发出通知。这是我的登录处理程序
class LoginManager {
private var auth: FirebaseAuth = Firebase.auth
fun loginWithEmail(
email: String,
password: String,
loginCallback: LoginCallback
) {
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener { loginTask ->
if (loginTask.isSuccessful) {
auth.currentUser?.let { user ->
loginCallback.onLoginSuccess(user)
return@addOnCompleteListener
}
}
loginCallback.onLoginFailure(loginTask.exception)
}
} }
LoginCallback 是一个简单的接口
interface LoginCallback {
fun onLoginSuccess(user: FirebaseUser)
fun onLoginFailure(error: Exception?) }
我需要测试 loginWithEmail
函数。在我的测试中,我尝试使用此代码
Handler(getMainLooper()).post {
var firebaseUser: FirebaseUser? = null
val loginCallback = object : LoginCallback {
override fun onLoginSuccess(user: FirebaseUser) {
firebaseUser = user
}
override fun onLoginFailure(error: Exception?) {
//No action needed
}
}
val loginManager = LoginManager(loginCallback)
loginManager.loginWithEmail(EXISTING_EMAIL_ADDRESS, CORRECT_PASSWORD)
Thread.sleep(5000)
assert(firebaseUser != null)
}
shadowOf(getMainLooper()).idle()
但是回调永远不会被调用。我也尝试使用 ArgumentCaptor
Handler(getMainLooper()).post {
val captor = ArgumentCaptor.forClass(LoginCallback::class.java)
val loginManager = LoginManager()
loginManager.loginWithEmail(EXISTING_EMAIL_ADDRESS, CORRECT_PASSWORD, captor.capture())
}
shadowOf(getMainLooper()).idle()
但是使用此代码,我收到此错误 java.lang.NullPointerException: captor.capture() must not be null
有没有办法测试我的功能?