MutableLiveData is null in JUnitTest
Add an executor InstantTaskExecutorRule()
as a member of the Test class
A JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously. You can use this rule for your host side tests that use Architecture Components.
//@RunWith(JUnit4::class) // For JUnit4
@ExtendWith(InstantExecutorExtension::class) // For JUnit5
class FilterViewModelTest {
@Rule @JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun test() {
//Here you don't ask if isMainThread
}
}
build.gradle(:mobile)
android {
//...
dependencies {
//...
testImplementation 'androidx.arch.core:core-testing:2.1.0'
androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
}
}
GL
InstantTaskExecutorRule
I had this error and solved it by adding InstantTaskExecutorRule:
private lateinit var contactProfileViewModel: ContactProfileViewModel
private val getStatusesForContact: GetStatusesForContact = mockk(relaxed = true)
private val getStory: GetUserLastStory = mockk(relaxed = true)
private val successStatusesCaptor = slot<((List<StatusDomain>) -> Unit)>()
private val successStoryCaptor = slot<((List<StoryDomain>) -> Unit)>()
@get:Rule
val rule: TestRule = InstantTaskExecutorRule()
@Before
fun setUp(){
contactProfileViewModel = ContactProfileViewModel(getStatusesForContact, getStory)
}
Looks like you are missing the android.arch.core:core-testing dependency.
testImplementation "android.arch.core:core-testing:1.1.1"
This allows you to use the InstantTaskExecutorRule in your test, which will get rid of the isMainThread call.
https://developer.android.com/reference/android/arch/core/executor/testing/InstantTaskExecutorRule.html
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();