title: Android Architecture Component ViewModel - How to mock ViewModel on test Activity?
body: <p>I'm trying to setup UI testing similar to <strong>GithubBrowserSample</strong> and it looks like the sample project only has mock <code>ViewModel</code> for <code>Fragment</code> but not an example for <code>Activity</code>.</p>
  
  <p>Here's my code where I am trying to test the <code>Activity</code> by mocking <code>ViewModel</code>. But the <code>ViewModel</code> is not getting set before <code>onCreate()</code> in Activity. </p>
  
  <pre><code>@RunWith(AndroidJUnit4::class)
  class MainActivityTest {
  
      val viewModel = mock(MainViewModel::class.java)
  
      @Rule
      @JvmField
      val activityRule = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java, true, true)
  
      private val liveData = MutableLiveData&lt;Resource&lt;Object&gt;&gt;()
  
      @Before
      open fun setUp() {
          activityRule.activity.viewModelFactory = createViewModelFor(viewModel)
          `when`(viewModel.liveData).thenReturn(liveData)
          viewModel.liveData?.observeForever(mock(Observer::class.java) as Observer&lt;Resource&lt;Object&gt;&gt;)
          liveData.postValue(Resource.success(Object()))
      }
  
      fun &lt;T : ViewModel&gt; createViewModelFor(model: T): ViewModelProvider.Factory =
          object : ViewModelProvider.Factory {
              override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T {
                  if (modelClass.isAssignableFrom(model.javaClass)) {
                      return model as T
                  }
                  throw IllegalArgumentException("unexpected model class " + modelClass)
              }
          }
  }
  </code></pre>
  
  <p>Can someone help me about this issue please?</p>