title: How to create Android UI Test for Android App Architecture ViewModels?
body: <p>I have been working with the new Android App Architecture Components. The documentation on testing leaves a lot to the imagination. I have looked at <a href="https://developer.android.com/topic/libraries/architecture/guide.html#testing" rel="nofollow noreferrer">android architecture components testing</a> part of the documentation it was very vague as worded below.</p>
  
  <p><strong>User Interface &amp; Interactions:</strong> This will be the only time you need an Android UI Instrumentation test. The best way to test UI code is to create an Espresso test. <strong>You can create the fragment and provide it a mock ViewModel.</strong> Since the fragment only talks to the ViewModel, mocking it will be sufficient to fully test this UI</p>
  
  <p>How do you go about writing a Espresso test by passing in a mock of a ViewModel to the fragment? I have also looked at the sample apps provided by Google they were also not very helpful.</p>
  
  <p>Suppose this is my example fragment class. </p>
  
  <pre><code>public class ExampleFragment extends LifecycleFragment {
      private ExampleViewModel mViewModel;
      @Inject ExampleViewModelFactory mViewModelFactory;
  
      public ExampleFragment() {
          // Required empty public constructor
      }
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {        
          return inflater.inflate(R.layout.fragment_example, container, false);  
      }
  
      @Override
      public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      ExampleComponent component = DaggerExampleComponent.builder().build();
      component.inject(this);
      mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(ExampleViewModel.class);
      mViewModel.getExampleString().observe(this, exampleString -&gt; {
         //Update UI
          });        
      }
  }  
  </code></pre>