title: How to simulate pressing the back button in Robolectric?
body: <p>Is there an easy way to simulate pressing the back button in Robolectric? </p>
  
  <p>The following test fails:</p>
  
  <pre><code>@Test
  public void testBackButtonClosesActivity() throws Exception {
      ShadowActivity activityShadow = Shadows.shadowOf(activity);
      activity.onKeyDown(KeyEvent.KEYCODE_BACK, new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, 0));
      assertTrue(activityShadow.isFinishing());
  }
  </code></pre>
  
  <p>However, this succeeds: </p>
  
  <pre><code>@Test
  public void testBackButtonClosesActivity() throws Exception {
      ShadowActivity activityShadow = Shadows.shadowOf(activity);
      activity.onBackPressed();
      assertTrue(activityShadow.isFinishing());
  }
  </code></pre>
  
  <p>This is in my activity to override <code>onKeyDown()</code>: </p>
  
  <pre><code>@Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK &amp; myCondition) {
          doStuff();
  
          return true;
      } else {
          return super.onKeyDown(keyCode, event);
      }
  }
  </code></pre>
  
  <p>Testing when <code>myCondition</code> is true triggers <code>doStuff()</code> in another test using <code>activity.onKeyDown(KeyEvent.KEYCODE_BACK, new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, 0));</code>. </p>
  
  <p>The activity is created using: </p>
  
  <pre><code>    Intent intent = new Intent(ShadowApplication.getInstance().getApplicationContext(), MyActivity.class);
      activity = Robolectric.buildActivity(MyActivity.class).withIntent(intent).create().visible().get();
  </code></pre>
  
  <p>I should point out that pressing the back button in the app when myCondition is false results in the activity closing. </p>