Facebook
From Thinh, 2 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 214
  1. class AuthRepositoryImpl @Inject constructor(
  2.     private val auth: FirebaseAuth,
  3.     private val dispatcher: CoroutineDispatcher = Dispatchers.IO
  4. ) : AuthRepository {
  5.     override fun signIn(email: String, password: String): Flow<Resource<FirebaseUser?&gt;> =
  6.         flow<Resource<FirebaseUser?&gt;> {
  7.             emit(Resource.Loading)
  8.             try {
  9.                 val result = auth.signInWithEmailAndPassword(email, password).await()
  10.                 val user = result.user
  11.                 if (user != null) {
  12.                     emit(Resource.success(user))
  13.                 } else {
  14.                     emit(Resource.failure(Exception("User is not exist")))
  15.                 }
  16.             } catch (e: Exception) {
  17.                 emit(Resource.failure(e))
  18.             }
  19.         }.flowOn(dispatcher)
  20. }
  21.  
  22. @ExperimentalCoroutinesApi
  23. class AuthRepositoryImplTest {
  24.  
  25.     @MockK
  26.     lateinit var firebaseAuth: FirebaseAuth
  27.  
  28.     private lateinit var authRepositoryImpl: AuthRepositoryImpl
  29.  
  30.     private val testDispatcher = StandardTestDispatcher()
  31.  
  32.     @Before
  33.     fun setUp() {
  34.         MockKAnnotations.init(this)
  35.         authRepositoryImpl = AuthRepositoryImpl(firebaseAuth, testDispatcher)
  36.     }
  37.  
  38.     @Test
  39.     fun `signIn with valid credentials emits success`(): Unit = runTest(testDispatcher) {
  40.         val email = "[email protected]"
  41.         val password = "123456"
  42.         val mockAuthResult: AuthResult = mockk(relaxed = true)
  43.         val mockUser: FirebaseUser = mockk(relaxed = true)
  44.  
  45.         coEvery {
  46.             firebaseAuth.signInWithEmailAndPassword(email, password).await()
  47.         } returns mockAuthResult
  48.         coEvery { mockAuthResult.user } returns mockUser
  49.  
  50.         val results = authRepositoryImpl.signIn(email, password).toList()
  51.  
  52.         // Kiểm tra kết quả có chứa Resource.Loading và Resource.Success hay không
  53.         assertTrue(results.first() is Resource.Loading)
  54.         assertTrue((results.last() as Resource.Success).value == mockUser)
  55.     }
  56.     }