我在应用程序的存储库层中具有暂停功能。我正在尝试对该功能进行单元测试,但是每次执行该功能时,它似乎都挂在await()
调用上,然后一直停留在那里,永远不会完成。似乎在后台发生了一些僵局,但现在还不清楚发生了什么。
有人在这里有解决方案吗?
这是我的回购功能:
suspend fun login(email: String, password: String): DataState<AuthViewState> {
try {
val authResult = firebaseAuth
.signInWithEmailAndPassword(email, password)
.await()
return DataState.data<AuthViewState>(
data = AuthViewState(
authResult.user?.uid
)
)
} catch (e: FirebaseAuthInvalidUserException) {
Log.e(TAG, "loginUserIfExisting: FirebaseAuthInvalidUserException: ", e)
return DataState.error<AuthViewState>(
"User not found. Please register."
)
} catch (e: FirebaseAuthInvalidCredentialsException) {
Log.e(TAG, "loginUserIfExisting: FirebaseAuthInvalidCredentialsException: ", e)
return DataState.error<AuthViewState>(
"Your password/email is incorrect. Please try again."
)
}
}
这是我的模拟测试:
@RunWith(JUnit4::class)
class AuthRepositoryTest {
private val email = "lee.a.wilson90@gmail.com"
private val password = "fakepassword"
private val CORRECT_USER_ID = "CORRECT_USER_ID"
private lateinit var SUT: AuthRepository
@Mock
private lateinit var firebaseAuth: FirebaseAuth
@Mock
private lateinit var authResultTask: Task<AuthResult>
@Mock
private lateinit var mockResult: AuthResult
@Mock
private lateinit var mockFirebaseUser: FirebaseUser
@Mock
private lateinit var mockUserPropertiesDao: UserPropertiesDao
@Mock
private lateinit var mockSharedPreferences: SharedPreferences
@Mock
private lateinit var mockSharedPreferencesEditor: SharedPreferences.Editor
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
`when`(firebaseAuth.signInWithEmailAndPassword(email, password))
.thenReturn(authResultTask)
`when`(mockResult.user)
.thenReturn(mockFirebaseUser)
`when`(mockFirebaseUser.uid)
.thenReturn("CORRECT_USER_ID")
`when`(mockUserPropertiesDao.searchByEmail(email))
.thenReturn(null)
`when`(mockSharedPreferences.getString(Constants.PREVIOUS_AUTH_USER, null))
.thenReturn(null)
SUT = AuthRepository(
firebaseAuth,
mockUserPropertiesDao,
mockSharedPreferences,
mockSharedPreferencesEditor
)
}
@Test
fun test_correctCredentialsEntered_correctOutputState() = runBlocking {
whenever(authResultTask.await()).thenReturn(mockResult)
val resultState = SUT.login(email, password)
val result = resultState.data!!.getContentIfNotHandled()!!.uid
assertEquals(CORRECT_USER_ID, result)
}
}
答案 0 :(得分:0)
Mockito似乎还不支持暂停功能。
因此,应该模拟TaskCompletionSource<AuthResult>
并设置其结果,而不是嘲笑authResultTask: Task<AuthResult>
(无论如何我都认为这是个坏主意)。
编辑:
通过对观察到的行为进行解释来完成此答案。
单元测试挂起,因为在模拟Continuation<T>.resume()
函数时,mockito未调用await()
。