Issue
I have login form which sign in the user using firebase and i'm trying to test the login functionality by writing some code and i used Mockito to mock the firebase class but for someone it keeps failing and i think there is something , if someone could help fix the issue , Thank you
- This is my code
@RunWith(AndroidJUnit4ClassRunner::class)
class LoginActivityTest {
@get:Rule
var scenario = ActivityScenarioRule(LoginActivity::class.java)
private lateinit var emailEditText : TextInputLayout
private lateinit var passwordEditText : TextInputLayout
private lateinit var firebaseUser: FirebaseUser
@Test
fun testCaseRealUserLogin(){
scenario.scenario.onActivity { it ->
emailEditText = it.findViewById(R.id.loginEmail)
passwordEditText = it.findViewById(R.id.loginPassword)
}
Looper.prepare()
emailEditText.editText!!.setText("[email protected]")
passwordEditText.editText!!.setText("xxxxxx")
onView(withId(R.id.loginBtn)).perform(click())
//Mocking firebase
val firebaseMock = mock(FirebaseAuth::class.java)
`when`(firebaseMock.signInWithEmailAndPassword("xxxxxxx","xxxxxxx"))
.thenReturn(notNull())
firebaseUser = firebaseMock.currentUser!!
assertNotNull(firebaseUser)
}
}
Solution
Simple Answer. the activity not using the mocked class!!. it uses the real one FirebaseAuth
.
So you need to supply the mocked class to the activity.
Simple approach is ServiceLocator pattern
First create a ServiceLocator.kt class
object ServiceLocator {
var auth = Firebase.auth
}
And use it in the production code instead of instantiating the auth
object
// in activity to sign in
ServiceLocator.auth.createUserWithEmailAndPassword(email, password)
Second you need to replace the real with the mocked class when testing
fun testCaseRealUserLogin(){
scenario.scenario.onActivity { it ->
emailEditText = it.findViewById(R.id.loginEmail)
passwordEditText = it.findViewById(R.id.loginPassword)
}
Looper.prepare()
emailEditText.editText!!.setText("[email protected]")
passwordEditText.editText!!.setText("xxxxxx")
//Mocking firebase
val firebaseMock = mock(FirebaseAuth::class.java)
// make activity using the mocked class here ---------------
ServiceLocator.auth = firebaseMock
onView(withId(R.id.loginBtn)).perform(click())
// this assertion will pass
`when`(firebaseMock.signInWithEmailAndPassword("xxxxxxx","xxxxxxx"))
.thenReturn(notNull())
firebaseUser = firebaseMock.currentUser!!
// NOTE: this assertion will fail as the mocked class will always return null and not the actual value
assertNotNull(firebaseUser)
}
Answered By - Hussien Fahmy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.