2

I am getting mockito wanted but not invoked. I don't know what to do cause Im new here :). by the way when I run the code in real device its okay.

Wanted but not invoked: observer.onChanged(true);

TestClass

 @RunWith(MockitoJUnitRunner::class)
    class LoginViewModelTest {

         var loginViewModel: LoginViewModel? = null
        @get:Rule
        val instantTaskExecutorRule = InstantTaskExecutorRule()
        @Mock
        lateinit var observer: Observer<Boolean>
        @Mock
        lateinit var dataManager: DataManager

        @Before
        fun setup() {
            MockitoAnnotations.initMocks(this)
            loginViewModel = LoginViewModel(dataManager)
        }

        @Test
        fun testApiFetchDataSuccess() {
            loginViewModel?.liveData?.observeForever(observer)
            loginViewModel?.login("test", "1234")
            verify(observer)?.onChanged(true)
        }

    }

ViewModelClass

class LoginViewModel(dataManager: DataManager?) : BaseViewModel() {

    var liveData: MutableLiveData<Boolean>
    var dataManager: DataManager? = dataManager

    init {
        liveData = MutableLiveData()
    }

    fun login(email: String, password: String) {
        dataManager?.getFireStoreManager()?.login(email, password)?.get()?.addOnSuccessListener {
            if (it.documents.size > 0) {
                val data = it.documents[0].toObject(User::class.java)
                liveData.postValue(true)
            } else {
                liveData.postValue(false)
            }
        }?.addOnFailureListener {
            liveData.postValue(false)
        }
    }
}
6155031
  • 4,171
  • 6
  • 27
  • 56
  • Firebase operations are usually asynchronous. You should not just mock your dataManager, but instruct it what to return when asked to return `getFireStoreManager()`. Mock a FireStoreManager as well, and then mock the task from the login. Hopefully this helps you. I am guessing that the `addOnSuccessListener` is never invoked, you can put a breakpoint there. – Giorgos Neokleous Sep 20 '19 at 08:49
  • @GiorgosNeokleous Can you write a sample code pls :) – 6155031 Sep 20 '19 at 10:03

1 Answers1

1

get() doesn't return anything because You mock dataManager which holds all the data.

In my case it looked like this:

`when`(collectionRef.document(ArgumentMatchers.anyString())).thenReturn(documentReference)
`when`(documentReference.get()).thenReturn(firestoreDocumentResult)

You just need to return mock for every method that Your dataManager will trigger.