Hey i want to test observer in mockk. Anyone know ...
# mockk
v
Hey i want to test observer in mockk. Anyone know how to do that.
Copy code
viewModel.onDownloadErrorLiveData.observe(this, { consumable ->
           some code
        })
m
You can get a reference to arguments passed in with
capture
in a verify block or in an
answers
block. Then just manually invoke the observer.
v
@Matt Thompson thanks for your reply. I am new in this library. I didn't get the reference or example. Can you please give me the example if possible. It would be great pleasure for me.
m
Sorry not on a proper keyboard but I'll try...
Copy code
```lateinit var observer : Observer
every { mockLiveData.observe(any(), any()) } answers { observer = secondArg() as Observer }
something like that
v
@Matt Thompson
Copy code
private fun yo(){
    viewModel.consentTag.observe(this, Observer { type ->
        typeText.text = type
    })
}
this is my function
Copy code
import androidx.lifecycle.Observer
which import i need to use
Copy code
@Test
fun `yo `() {
    every { mockViewModel.consentTag.observe(any(), any()) } answers {
        observer = secondArg() as Observer
    }

}
it giving error
m
you need to add the generic type of the LiveData
i.e.
Observer<TypeHere>
v
okk
it fixed on complaining in observer issue
it again complaining this @Matt Thompson
ConsentType is enum class
m
yeah when you cast it using
as
you also need to define the type
or alternatively I believe
secondArg
takes a type argument, you could try putting it there
v
Sorry for again asking this
Copy code
observer = secondArg() as ConsentType
like this ?
m
no,
as Observer<ConsentType>
the actual type of the lambda that you’re passing in as the second argument of the
observe
function is
Observer<ConsentType>
- kotlin allows you to write it as a lambda with SAM conversion
v
and little bit confuse
Copy code
private fun yo(){
    viewModel.consentTag.observe(this, Observer { type ->
        typeText.text = type
    })
}
how can i set value
type
in typeText
m
once you have the reference to the observer you can manually invoke
onChanged
v
@Matt Thompson like this
Copy code
@Test
    fun `yo `() {
        val value = ConsentType.GENERAL
        every { mockViewModel.consentTag.observe(any(), any()) } answers {
            observer = secondArg() as Observer<ConsentType>
        }
        observer.onChanged(value)
        consentActivity.yo()
        verify { mockTextView.tag = value }
    }
it gives error
kotlin.UninitializedPropertyAccessException: lateinit property observer has not been initialized
m
yeah that makes sense - the way
every
/
answers
works is that the
answers
block with be run every time the function inside of
every
gets called. so if this
yo
function is what calls it, you need to call it in order to initialize your
observer
var
v
So i need to call
yo
at top of function ?