Home > Net >  mock a database reference callback with mockito
mock a database reference callback with mockito

Time:01-09

I'm trying to test database reference by retrieving simple user info , i tried to mock the database references and apply mockito logic on it but for some reason it is not working , the pass is failing , i'm still new with mockito if someone could help thank you , can you please show me how to mock addValuelistener with mockito

  • This is my code

ServiceLocator
          .db_reference
          .child("Users")
          .child(ServiceLocator.auth.currentUser!!.uid)
          .addListenerForSingleValueEvent(object  : ValueEventListener{
              override fun onDataChange(snapshot: DataSnapshot) {
                  if(snapshot.exists()){
                     /// getting data
                  }
              }

              override fun onCancelled(error: DatabaseError) {

              }

          })

  • This is the test code
  @Test
   fun h_testCaseGetUserInfoFromDB(){
       val firebaseMock = mock(FirebaseAuth::class.java)
       val databaseMock = mock(DatabaseReference::class.java)

       ServiceLocator.auth = firebaseMock
       ServiceLocator.db_reference = databaseMock


       `when`(databaseMock.child("Users").child(firebaseMock.currentUser!!.uid).get()).thenReturn(
           isNotNull())

   }

CodePudding user response:

Please consider the following note about mocks

Mocks is not a real implementation and doesn't know anything about it.
It used mainly for checking that a certain action WILL happens i.e. asserting that a certain function have received a certain parameters, with out any guarantee that this function will perform successfully in the real implementation.
Also Note it doesn't return any value like real implementation.

So in your code you are testing that a certain data existing in your real firebase. so you need to test with the real firebase instance, there is no work for Mocks to do here. So don't use it

  •  Tags:  
  • Related