I try to follow sample code but look like it not working to me. Can somebody help me check my code what I am wrong?
@RunWith(AndroidJUnit4::class)
class AFragmentTest {
@Rule
@JvmField
val activityRule = ActivityTestRule(MainActivity::class.java, true, true)
private lateinit var fragment: AFragment
private val viewModel = mock(AViewModel::class.java)
private val listener = mock(AFragment.OnInteractionListener::class.java)
private val liveData = MutableLiveData<Resource<A>>()
@Before
fun setUp() {
fragment = AFragment()
fragment.viewModel = viewModel
`when`(viewModel.liveData).thenReturn(liveData)
fragment.listener = listener
activityRule.activity.replaceFragment(fragment)
}
@Test
fun aTestSomeThing() {
val a = A()
liveData.postValue(Resource.success(a))
verify(listener)?.onSuccess(a)
}
}
If add sleep to wait for postValue() it working. But I think we should not do like this.
liveData.postValue(Resource.success(a))
sleep(1000)
Here is a solution that is working for me (so far!) after browsing the source for this test suite.
androidTestImplementation "androidx.arch.core:core-testing:2.0.0"@get:Rule val countingTaskExecutorRule = CountingTaskExecutorRule()liveData.postValue(), call: countingTaskExecutorRule.drainTasks(3, TimeUnit.SECONDS) (adjust the timeout to your liking) to wait for the tasks to all complete. Your test class above would look like this:
@RunWith(AndroidJUnit4::class)
class AFragmentTest {
@Rule
@JvmField
val activityRule = ActivityTestRule(MainActivity::class.java, true, true)
@Rule
@JvmField
val countingTaskExecutorRule = CountingTaskExecutorRule()
private lateinit var fragment: AFragment
private val viewModel = mock(AViewModel::class.java)
private val listener = mock(AFragment.OnInteractionListener::class.java)
private val liveData = MutableLiveData<Resource<A>>()
@Before
fun setUp() {
fragment = AFragment()
fragment.viewModel = viewModel
`when`(viewModel.liveData).thenReturn(liveData)
fragment.listener = listener
activityRule.activity.replaceFragment(fragment)
}
@Test
fun aTestSomeThing() {
val a = A()
liveData.postValue(Resource.success(a))
countingTaskExecutorRule.drainTasks(3, TimeUnit.SECONDS)
verify(listener)?.onSuccess(a)
}
}
I found this solution from browsing this repo and found this test.
CountingTaskExecutorRule is the correct class to use, yep.
Most helpful comment
Here is a solution that is working for me (so far!) after browsing the source for this test suite.
androidTestImplementation "androidx.arch.core:core-testing:2.0.0"@get:Rule val countingTaskExecutorRule = CountingTaskExecutorRule()liveData.postValue(), call:countingTaskExecutorRule.drainTasks(3, TimeUnit.SECONDS)(adjust the timeout to your liking) to wait for the tasks to all complete.Your test class above would look like this:
I found this solution from browsing this repo and found this test.