2021年4月11日星期日

Robolectric start a fragment that has an observer

I'm trying to run a unit test on a fragment with Robolectic, the fragment has a liveData observer that is preventing the test from completing. If I were to remove the observer from the fragment the test passes.

With the observer in the fragment, I get the following error. Error when running test.

java.lang.Exception: Main looper has queued unexecuted runnables. This might be the cause of the test failure. You might need a shadowOf(getMainLooper()).idle() call.    

Fragment

class MyFragment(private val viewModel: MyViewModel) : Fragment() {        override fun onCreate(          infalter: LayoutInfalter,          container: ViewGroup?,          savedInstanceState: Bundle?      ) : View? {            ...           // If I remove this observer the test will pass.           viewModel.MyLiveData.observe(viewLifecycleOwner, {              ...          }      }  }  

My Test

@RunWith(robolectricTestRunner::class)   class MyFragmentTest {        // Executes tasks in the Architecture Components in the same thread      @get:Rule      var instantTaskExecutorRule = InstantTaskExecutorRule()        private lateinit var scenario: FragmentScenario<MyFragment>        @Before      fun setup() {          val viewModel: MyViewModel = mock(MyViewModel::class.java)          scenario = launchFragmentInContainer(              factory = MainFragmentFactory(viewModel),              fragmentArgs = null              themeResId = R.style.Theme_MyTheme          )          // Tried implementing shadowOf as the error suggests.           shadowOf(Looper.getMainLooper()).idle()      }        @Test      fun testOne() {          // Test is empty, to confirm that the test can run.       }   }  

I've tried the following

  • implementing a shadow class for the Main Looper. Annotating the class with Looper mode.
@RunWith(RobolectricTestRunner::class)  @LooperMode(LooperMode.Mode.PAUSED)  class MyFragmentTest {  
  • Adding scenario states
    scenario.moveToState(Lifecycle.State.CREATED)      scenario.moveToState(Lifecycle.State.RESUMED)  

Links I've used to find a solution' Testing LiveData Transformations?

https://stackoverflow.com/questions/67029616/robolectric-start-a-fragment-that-has-an-observer April 10, 2021 at 07:59AM

没有评论:

发表评论