title: Testing Android Fragments
body: <p>I have a business logic in UI-less fragment which I have to test. I have tried 2 options and both have failed.</p>
  
  <p><strong>1. Use AndroidTestCase and create mock activity.</strong></p>
  
  <p>Following code</p>
  
  <pre><code>@Override
  protected void setUp() {
      Intent i = new Intent(getTestContext(), TestActivity.class);
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      getTestContext().startActivity(i);
  }
  </code></pre>
  
  <p>throws an exception </p>
  
  <pre><code>Permission denied: checkComponentPermission() reqUid=10104
  java.lang.SecurityException: Permission Denial: starting Intent { flg=0x10000000 cmp=com.xxx.iabsample.test/.TestActivity } from ProcessRecord{40769510 28116:com.xxx.iabsample/10070  (pid=28116, uid=10070) requires null
  </code></pre>
  
  <p><strong>2. Use ActivityInstrumentationTestCase2 with mock activity</strong></p>
  
  <p>Code</p>
  
  <pre><code>public class IabTest extends ActivityInstrumentationTestCase2&lt;TestActivity&gt; {
      public IabTest() {
          super("com.xxx.iabsample.test", TestActivity.class);
      }
  }
  </code></pre>
  
  <p>throws an exception</p>
  
  <pre><code>java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.xxx.iabsample/.test.TestActivity }
  </code></pre>
  
  <p>It seems that it tries to start activity from test-target app, not from the test app.</p>
  
  <p>So, what is the correct way to test fragments?</p>