Android - Independent Fragment UI testing tool





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







16















I've been looking for a way to test the UI of my Fragments separately (ie, independently from other fragments and activities) but I can't find a way to do it.



In particular, let's say I have Fragment A, Fragment B and Fragment C. The only way (app-wise) to go to Fragment C is by passing through Fragment A and Fragment B first. I am looking for a way to test Fragment C directly (potentially by mocking its dependencies, if any exists), without having to pass through Fragment A and B.



Tools I investigated so far:




  • monkey: only used to generate pseudo-random events through command line. Not what I want.


  • monkeyrunner: it can run Python programs to send event streams to my Android app, but it cannot target a particular Fragment directly with those scripts.


  • Espresso: white-box testing tool. This comes close to what I want, but it still requires passing through Fragment A and B before reaching Fragment C (ie, you need to start your app and then the tests will run from there).


  • UI Automator: black-box testing tool. This also comes close, but again, it requires passing through the previous Fragments before testing the one I want (Fragment C).



Is there any way to test the UI of a Fragment directly?










share|improve this question





























    16















    I've been looking for a way to test the UI of my Fragments separately (ie, independently from other fragments and activities) but I can't find a way to do it.



    In particular, let's say I have Fragment A, Fragment B and Fragment C. The only way (app-wise) to go to Fragment C is by passing through Fragment A and Fragment B first. I am looking for a way to test Fragment C directly (potentially by mocking its dependencies, if any exists), without having to pass through Fragment A and B.



    Tools I investigated so far:




    • monkey: only used to generate pseudo-random events through command line. Not what I want.


    • monkeyrunner: it can run Python programs to send event streams to my Android app, but it cannot target a particular Fragment directly with those scripts.


    • Espresso: white-box testing tool. This comes close to what I want, but it still requires passing through Fragment A and B before reaching Fragment C (ie, you need to start your app and then the tests will run from there).


    • UI Automator: black-box testing tool. This also comes close, but again, it requires passing through the previous Fragments before testing the one I want (Fragment C).



    Is there any way to test the UI of a Fragment directly?










    share|improve this question

























      16












      16








      16


      11






      I've been looking for a way to test the UI of my Fragments separately (ie, independently from other fragments and activities) but I can't find a way to do it.



      In particular, let's say I have Fragment A, Fragment B and Fragment C. The only way (app-wise) to go to Fragment C is by passing through Fragment A and Fragment B first. I am looking for a way to test Fragment C directly (potentially by mocking its dependencies, if any exists), without having to pass through Fragment A and B.



      Tools I investigated so far:




      • monkey: only used to generate pseudo-random events through command line. Not what I want.


      • monkeyrunner: it can run Python programs to send event streams to my Android app, but it cannot target a particular Fragment directly with those scripts.


      • Espresso: white-box testing tool. This comes close to what I want, but it still requires passing through Fragment A and B before reaching Fragment C (ie, you need to start your app and then the tests will run from there).


      • UI Automator: black-box testing tool. This also comes close, but again, it requires passing through the previous Fragments before testing the one I want (Fragment C).



      Is there any way to test the UI of a Fragment directly?










      share|improve this question














      I've been looking for a way to test the UI of my Fragments separately (ie, independently from other fragments and activities) but I can't find a way to do it.



      In particular, let's say I have Fragment A, Fragment B and Fragment C. The only way (app-wise) to go to Fragment C is by passing through Fragment A and Fragment B first. I am looking for a way to test Fragment C directly (potentially by mocking its dependencies, if any exists), without having to pass through Fragment A and B.



      Tools I investigated so far:




      • monkey: only used to generate pseudo-random events through command line. Not what I want.


      • monkeyrunner: it can run Python programs to send event streams to my Android app, but it cannot target a particular Fragment directly with those scripts.


      • Espresso: white-box testing tool. This comes close to what I want, but it still requires passing through Fragment A and B before reaching Fragment C (ie, you need to start your app and then the tests will run from there).


      • UI Automator: black-box testing tool. This also comes close, but again, it requires passing through the previous Fragments before testing the one I want (Fragment C).



      Is there any way to test the UI of a Fragment directly?







      android android-testing android-espresso uiautomator android-uiautomator






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 '15 at 8:58









      TiagoTiago

      6,09955280




      6,09955280
























          4 Answers
          4






          active

          oldest

          votes


















          49














          I'm am using a custom FragmentTestRule and Espresso to test each of my Fragments in isolation.



          I have a dedicated TestActivity that shows the tested Fragments in my app. In my case the Activity only exists in the debug variant because my instrumentation tests run against debug.



          TL;DR Use the awesome FragmentTestRule library by @brais-gabin.



          1. Create a TestActivity in src/debug/java/your/package/TestActivity.java with a content view where the tested Fragment will be added to:



          @VisibleForTesting
          public class TestActivity extends AppCompatActivity {
          @Override
          protected void onCreate(@Nullable final Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          FrameLayout frameLayout = new FrameLayout(this);
          frameLayout.setId(R.id.container);
          setContentView(frameLayout);
          }
          }


          2. Create a AndroidManifest.xml for the debug variant and declare the TestActivity. This is required to start the TestActivity when testing. Add this Manifest to the debug variant in src/debug/AndroidManifest.xml:



          <?xml version="1.0" encoding="utf-8"?>
          <manifest xmlns:android="http://schemas.android.com/apk/res/android">
          <application>
          <activity android:name="your.package.TestActivity"/>
          </application>
          </manifest>


          3. Create the FragmentTestRule in the androidTest variant at src/androidTest/java/your/test/package/FragmentTestRule.java:



          public class FragmentTestRule<F extends Fragment> extends ActivityTestRule<TestActivity> {

          private final Class<F> mFragmentClass;
          private F mFragment;

          public FragmentTestRule(final Class<F> fragmentClass) {
          super(TestActivity.class, true, false);
          mFragmentClass = fragmentClass;
          }

          @Override
          protected void afterActivityLaunched() {
          super.afterActivityLaunched();

          getActivity().runOnUiThread(() -> {
          try {
          //Instantiate and insert the fragment into the container layout
          FragmentManager manager = getActivity().getSupportFragmentManager();
          FragmentTransaction transaction = manager.beginTransaction();
          mFragment = mFragmentClass.newInstance();
          transaction.replace(R.id.container, mFragment);
          transaction.commit();
          } catch (InstantiationException | IllegalAccessException e) {
          Assert.fail(String.format("%s: Could not insert %s into TestActivity: %s",
          getClass().getSimpleName(),
          mFragmentClass.getSimpleName(),
          e.getMessage()));
          }
          });
          }
          public F getFragment(){
          return mFragment;
          }
          }


          4. Then you can test Fragments in isolation:



          public class MyFragmentTest {

          @Rule
          public FragmentTestRule<MyFragment> mFragmentTestRule = new FragmentTestRule<>(MyFragment.class);

          @Test
          public void fragment_can_be_instantiated() {

          // Launch the activity to make the fragment visible
          mFragmentTestRule.launchActivity(null);

          // Then use Espresso to test the Fragment
          onView(withId(R.id.an_id_in_the_fragment)).check(matches(isDisplayed()));
          }
          }





          share|improve this answer





















          • 1





            the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

            – Ewoks
            Jul 5 '17 at 6:54





















          2














          I developed FragmentTestRule an Andorid library using the @thaussma's idea. It allows you to test your Fragments in isolation.



          You just need to add this:



          @Rule
          public FragmentTestRule<?, FragmentWithoutActivityDependency> fragmentTestRule =
          FragmentTestRule.create(FragmentWithoutActivityDependency.class);


          More information here.






          share|improve this answer































            1














            You can use Robotium.This is for android UI testing.






            share|improve this answer



















            • 1





              But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

              – Tiago
              Nov 11 '15 at 9:11











            • As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

              – Almett
              Nov 11 '15 at 9:35











            • @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

              – Almett
              Nov 11 '15 at 9:37



















            0














            If you are using the Navigation Architecture component and you are using a single activity architecture in your app, you can quickly test each fragment by Deep linking to the target fragment (with appropriate arguments) at the beginning of the test.



            For example:



            @Rule
            @JvmField
            var activityRule = ActivityTestRule(MainActivity::class.java)

            protected fun launchFragment(destinationId: Int,
            argBundle: Bundle? = null) {
            val launchFragmentIntent = buildLaunchFragmentIntent(destinationId, argBundle)
            activityRule.launchActivity(launchFragmentIntent)
            }

            private fun buildLaunchFragmentIntent(destinationId: Int, argBundle: Bundle?): Intent =
            NavDeepLinkBuilder(InstrumentationRegistry.getInstrumentation().targetContext)
            .setGraph(R.navigation.navigation)
            .setComponentName(MainActivity::class.java)
            .setDestination(destinationId)
            .setArguments(argBundle)
            .createTaskStackBuilder().intents[0]


            destinationId being the fragment destination id in the navigation graph. Here is an example of a call that would be done once you are ready to launch the fragment:



            launchFragment(R.id.target_fragment, targetBundle())

            private fun targetBundle(): Bundle? {
            val bundle = Bundle()
            bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
            return bundle
            }


            Doing it this way will launch the fragment directly. If your test works, then this proves that your app won't crash when the fragment is deep-linked to. It also ensures that the app will be stable if the process is killed by the system and it tries to rebuild the stack and relaunch the fragment.






            share|improve this answer


























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33647135%2fandroid-independent-fragment-ui-testing-tool%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              49














              I'm am using a custom FragmentTestRule and Espresso to test each of my Fragments in isolation.



              I have a dedicated TestActivity that shows the tested Fragments in my app. In my case the Activity only exists in the debug variant because my instrumentation tests run against debug.



              TL;DR Use the awesome FragmentTestRule library by @brais-gabin.



              1. Create a TestActivity in src/debug/java/your/package/TestActivity.java with a content view where the tested Fragment will be added to:



              @VisibleForTesting
              public class TestActivity extends AppCompatActivity {
              @Override
              protected void onCreate(@Nullable final Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              FrameLayout frameLayout = new FrameLayout(this);
              frameLayout.setId(R.id.container);
              setContentView(frameLayout);
              }
              }


              2. Create a AndroidManifest.xml for the debug variant and declare the TestActivity. This is required to start the TestActivity when testing. Add this Manifest to the debug variant in src/debug/AndroidManifest.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <manifest xmlns:android="http://schemas.android.com/apk/res/android">
              <application>
              <activity android:name="your.package.TestActivity"/>
              </application>
              </manifest>


              3. Create the FragmentTestRule in the androidTest variant at src/androidTest/java/your/test/package/FragmentTestRule.java:



              public class FragmentTestRule<F extends Fragment> extends ActivityTestRule<TestActivity> {

              private final Class<F> mFragmentClass;
              private F mFragment;

              public FragmentTestRule(final Class<F> fragmentClass) {
              super(TestActivity.class, true, false);
              mFragmentClass = fragmentClass;
              }

              @Override
              protected void afterActivityLaunched() {
              super.afterActivityLaunched();

              getActivity().runOnUiThread(() -> {
              try {
              //Instantiate and insert the fragment into the container layout
              FragmentManager manager = getActivity().getSupportFragmentManager();
              FragmentTransaction transaction = manager.beginTransaction();
              mFragment = mFragmentClass.newInstance();
              transaction.replace(R.id.container, mFragment);
              transaction.commit();
              } catch (InstantiationException | IllegalAccessException e) {
              Assert.fail(String.format("%s: Could not insert %s into TestActivity: %s",
              getClass().getSimpleName(),
              mFragmentClass.getSimpleName(),
              e.getMessage()));
              }
              });
              }
              public F getFragment(){
              return mFragment;
              }
              }


              4. Then you can test Fragments in isolation:



              public class MyFragmentTest {

              @Rule
              public FragmentTestRule<MyFragment> mFragmentTestRule = new FragmentTestRule<>(MyFragment.class);

              @Test
              public void fragment_can_be_instantiated() {

              // Launch the activity to make the fragment visible
              mFragmentTestRule.launchActivity(null);

              // Then use Espresso to test the Fragment
              onView(withId(R.id.an_id_in_the_fragment)).check(matches(isDisplayed()));
              }
              }





              share|improve this answer





















              • 1





                the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

                – Ewoks
                Jul 5 '17 at 6:54


















              49














              I'm am using a custom FragmentTestRule and Espresso to test each of my Fragments in isolation.



              I have a dedicated TestActivity that shows the tested Fragments in my app. In my case the Activity only exists in the debug variant because my instrumentation tests run against debug.



              TL;DR Use the awesome FragmentTestRule library by @brais-gabin.



              1. Create a TestActivity in src/debug/java/your/package/TestActivity.java with a content view where the tested Fragment will be added to:



              @VisibleForTesting
              public class TestActivity extends AppCompatActivity {
              @Override
              protected void onCreate(@Nullable final Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              FrameLayout frameLayout = new FrameLayout(this);
              frameLayout.setId(R.id.container);
              setContentView(frameLayout);
              }
              }


              2. Create a AndroidManifest.xml for the debug variant and declare the TestActivity. This is required to start the TestActivity when testing. Add this Manifest to the debug variant in src/debug/AndroidManifest.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <manifest xmlns:android="http://schemas.android.com/apk/res/android">
              <application>
              <activity android:name="your.package.TestActivity"/>
              </application>
              </manifest>


              3. Create the FragmentTestRule in the androidTest variant at src/androidTest/java/your/test/package/FragmentTestRule.java:



              public class FragmentTestRule<F extends Fragment> extends ActivityTestRule<TestActivity> {

              private final Class<F> mFragmentClass;
              private F mFragment;

              public FragmentTestRule(final Class<F> fragmentClass) {
              super(TestActivity.class, true, false);
              mFragmentClass = fragmentClass;
              }

              @Override
              protected void afterActivityLaunched() {
              super.afterActivityLaunched();

              getActivity().runOnUiThread(() -> {
              try {
              //Instantiate and insert the fragment into the container layout
              FragmentManager manager = getActivity().getSupportFragmentManager();
              FragmentTransaction transaction = manager.beginTransaction();
              mFragment = mFragmentClass.newInstance();
              transaction.replace(R.id.container, mFragment);
              transaction.commit();
              } catch (InstantiationException | IllegalAccessException e) {
              Assert.fail(String.format("%s: Could not insert %s into TestActivity: %s",
              getClass().getSimpleName(),
              mFragmentClass.getSimpleName(),
              e.getMessage()));
              }
              });
              }
              public F getFragment(){
              return mFragment;
              }
              }


              4. Then you can test Fragments in isolation:



              public class MyFragmentTest {

              @Rule
              public FragmentTestRule<MyFragment> mFragmentTestRule = new FragmentTestRule<>(MyFragment.class);

              @Test
              public void fragment_can_be_instantiated() {

              // Launch the activity to make the fragment visible
              mFragmentTestRule.launchActivity(null);

              // Then use Espresso to test the Fragment
              onView(withId(R.id.an_id_in_the_fragment)).check(matches(isDisplayed()));
              }
              }





              share|improve this answer





















              • 1





                the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

                – Ewoks
                Jul 5 '17 at 6:54
















              49












              49








              49







              I'm am using a custom FragmentTestRule and Espresso to test each of my Fragments in isolation.



              I have a dedicated TestActivity that shows the tested Fragments in my app. In my case the Activity only exists in the debug variant because my instrumentation tests run against debug.



              TL;DR Use the awesome FragmentTestRule library by @brais-gabin.



              1. Create a TestActivity in src/debug/java/your/package/TestActivity.java with a content view where the tested Fragment will be added to:



              @VisibleForTesting
              public class TestActivity extends AppCompatActivity {
              @Override
              protected void onCreate(@Nullable final Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              FrameLayout frameLayout = new FrameLayout(this);
              frameLayout.setId(R.id.container);
              setContentView(frameLayout);
              }
              }


              2. Create a AndroidManifest.xml for the debug variant and declare the TestActivity. This is required to start the TestActivity when testing. Add this Manifest to the debug variant in src/debug/AndroidManifest.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <manifest xmlns:android="http://schemas.android.com/apk/res/android">
              <application>
              <activity android:name="your.package.TestActivity"/>
              </application>
              </manifest>


              3. Create the FragmentTestRule in the androidTest variant at src/androidTest/java/your/test/package/FragmentTestRule.java:



              public class FragmentTestRule<F extends Fragment> extends ActivityTestRule<TestActivity> {

              private final Class<F> mFragmentClass;
              private F mFragment;

              public FragmentTestRule(final Class<F> fragmentClass) {
              super(TestActivity.class, true, false);
              mFragmentClass = fragmentClass;
              }

              @Override
              protected void afterActivityLaunched() {
              super.afterActivityLaunched();

              getActivity().runOnUiThread(() -> {
              try {
              //Instantiate and insert the fragment into the container layout
              FragmentManager manager = getActivity().getSupportFragmentManager();
              FragmentTransaction transaction = manager.beginTransaction();
              mFragment = mFragmentClass.newInstance();
              transaction.replace(R.id.container, mFragment);
              transaction.commit();
              } catch (InstantiationException | IllegalAccessException e) {
              Assert.fail(String.format("%s: Could not insert %s into TestActivity: %s",
              getClass().getSimpleName(),
              mFragmentClass.getSimpleName(),
              e.getMessage()));
              }
              });
              }
              public F getFragment(){
              return mFragment;
              }
              }


              4. Then you can test Fragments in isolation:



              public class MyFragmentTest {

              @Rule
              public FragmentTestRule<MyFragment> mFragmentTestRule = new FragmentTestRule<>(MyFragment.class);

              @Test
              public void fragment_can_be_instantiated() {

              // Launch the activity to make the fragment visible
              mFragmentTestRule.launchActivity(null);

              // Then use Espresso to test the Fragment
              onView(withId(R.id.an_id_in_the_fragment)).check(matches(isDisplayed()));
              }
              }





              share|improve this answer















              I'm am using a custom FragmentTestRule and Espresso to test each of my Fragments in isolation.



              I have a dedicated TestActivity that shows the tested Fragments in my app. In my case the Activity only exists in the debug variant because my instrumentation tests run against debug.



              TL;DR Use the awesome FragmentTestRule library by @brais-gabin.



              1. Create a TestActivity in src/debug/java/your/package/TestActivity.java with a content view where the tested Fragment will be added to:



              @VisibleForTesting
              public class TestActivity extends AppCompatActivity {
              @Override
              protected void onCreate(@Nullable final Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              FrameLayout frameLayout = new FrameLayout(this);
              frameLayout.setId(R.id.container);
              setContentView(frameLayout);
              }
              }


              2. Create a AndroidManifest.xml for the debug variant and declare the TestActivity. This is required to start the TestActivity when testing. Add this Manifest to the debug variant in src/debug/AndroidManifest.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <manifest xmlns:android="http://schemas.android.com/apk/res/android">
              <application>
              <activity android:name="your.package.TestActivity"/>
              </application>
              </manifest>


              3. Create the FragmentTestRule in the androidTest variant at src/androidTest/java/your/test/package/FragmentTestRule.java:



              public class FragmentTestRule<F extends Fragment> extends ActivityTestRule<TestActivity> {

              private final Class<F> mFragmentClass;
              private F mFragment;

              public FragmentTestRule(final Class<F> fragmentClass) {
              super(TestActivity.class, true, false);
              mFragmentClass = fragmentClass;
              }

              @Override
              protected void afterActivityLaunched() {
              super.afterActivityLaunched();

              getActivity().runOnUiThread(() -> {
              try {
              //Instantiate and insert the fragment into the container layout
              FragmentManager manager = getActivity().getSupportFragmentManager();
              FragmentTransaction transaction = manager.beginTransaction();
              mFragment = mFragmentClass.newInstance();
              transaction.replace(R.id.container, mFragment);
              transaction.commit();
              } catch (InstantiationException | IllegalAccessException e) {
              Assert.fail(String.format("%s: Could not insert %s into TestActivity: %s",
              getClass().getSimpleName(),
              mFragmentClass.getSimpleName(),
              e.getMessage()));
              }
              });
              }
              public F getFragment(){
              return mFragment;
              }
              }


              4. Then you can test Fragments in isolation:



              public class MyFragmentTest {

              @Rule
              public FragmentTestRule<MyFragment> mFragmentTestRule = new FragmentTestRule<>(MyFragment.class);

              @Test
              public void fragment_can_be_instantiated() {

              // Launch the activity to make the fragment visible
              mFragmentTestRule.launchActivity(null);

              // Then use Espresso to test the Fragment
              onView(withId(R.id.an_id_in_the_fragment)).check(matches(isDisplayed()));
              }
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 16 '18 at 22:51

























              answered Jul 15 '16 at 9:51









              thaussmathaussma

              8,52033340




              8,52033340








              • 1





                the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

                – Ewoks
                Jul 5 '17 at 6:54
















              • 1





                the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

                – Ewoks
                Jul 5 '17 at 6:54










              1




              1





              the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

              – Ewoks
              Jul 5 '17 at 6:54







              the only "little" thing is that your test code is mixed with productive/runtime code (at least in debug build) which can easily and very fast get messy as you add more tests to the suite :( Probably workaround if better solution doesn't exist is to leave just manifest entry in debug build and to keep classes (TestActivity, Rule, etc..) in androidTest

              – Ewoks
              Jul 5 '17 at 6:54















              2














              I developed FragmentTestRule an Andorid library using the @thaussma's idea. It allows you to test your Fragments in isolation.



              You just need to add this:



              @Rule
              public FragmentTestRule<?, FragmentWithoutActivityDependency> fragmentTestRule =
              FragmentTestRule.create(FragmentWithoutActivityDependency.class);


              More information here.






              share|improve this answer




























                2














                I developed FragmentTestRule an Andorid library using the @thaussma's idea. It allows you to test your Fragments in isolation.



                You just need to add this:



                @Rule
                public FragmentTestRule<?, FragmentWithoutActivityDependency> fragmentTestRule =
                FragmentTestRule.create(FragmentWithoutActivityDependency.class);


                More information here.






                share|improve this answer


























                  2












                  2








                  2







                  I developed FragmentTestRule an Andorid library using the @thaussma's idea. It allows you to test your Fragments in isolation.



                  You just need to add this:



                  @Rule
                  public FragmentTestRule<?, FragmentWithoutActivityDependency> fragmentTestRule =
                  FragmentTestRule.create(FragmentWithoutActivityDependency.class);


                  More information here.






                  share|improve this answer













                  I developed FragmentTestRule an Andorid library using the @thaussma's idea. It allows you to test your Fragments in isolation.



                  You just need to add this:



                  @Rule
                  public FragmentTestRule<?, FragmentWithoutActivityDependency> fragmentTestRule =
                  FragmentTestRule.create(FragmentWithoutActivityDependency.class);


                  More information here.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 16 '17 at 8:38









                  Brais GabinBrais Gabin

                  3,81434079




                  3,81434079























                      1














                      You can use Robotium.This is for android UI testing.






                      share|improve this answer



















                      • 1





                        But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

                        – Tiago
                        Nov 11 '15 at 9:11











                      • As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

                        – Almett
                        Nov 11 '15 at 9:35











                      • @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

                        – Almett
                        Nov 11 '15 at 9:37
















                      1














                      You can use Robotium.This is for android UI testing.






                      share|improve this answer



















                      • 1





                        But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

                        – Tiago
                        Nov 11 '15 at 9:11











                      • As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

                        – Almett
                        Nov 11 '15 at 9:35











                      • @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

                        – Almett
                        Nov 11 '15 at 9:37














                      1












                      1








                      1







                      You can use Robotium.This is for android UI testing.






                      share|improve this answer













                      You can use Robotium.This is for android UI testing.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 11 '15 at 9:06









                      AlmettAlmett

                      554527




                      554527








                      • 1





                        But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

                        – Tiago
                        Nov 11 '15 at 9:11











                      • As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

                        – Almett
                        Nov 11 '15 at 9:35











                      • @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

                        – Almett
                        Nov 11 '15 at 9:37














                      • 1





                        But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

                        – Tiago
                        Nov 11 '15 at 9:11











                      • As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

                        – Almett
                        Nov 11 '15 at 9:35











                      • @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

                        – Almett
                        Nov 11 '15 at 9:37








                      1




                      1





                      But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

                      – Tiago
                      Nov 11 '15 at 9:11





                      But Robotium has the same problem as UI Automator and Espresso. In order to test Fragment C, I need to pass through Fragment A and B first. I want a tool that allows me to test Fragment C directly.

                      – Tiago
                      Nov 11 '15 at 9:11













                      As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

                      – Almett
                      Nov 11 '15 at 9:35





                      As i have been using robotium,it solves any kind of UI testing problem.I dont know the details of your requirement ,so please check robotium API robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html

                      – Almett
                      Nov 11 '15 at 9:35













                      @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

                      – Almett
                      Nov 11 '15 at 9:37





                      @Tiago I hope APIs like waitForFragmentByTag, waitForFragmentById can help you. Good luck.

                      – Almett
                      Nov 11 '15 at 9:37











                      0














                      If you are using the Navigation Architecture component and you are using a single activity architecture in your app, you can quickly test each fragment by Deep linking to the target fragment (with appropriate arguments) at the beginning of the test.



                      For example:



                      @Rule
                      @JvmField
                      var activityRule = ActivityTestRule(MainActivity::class.java)

                      protected fun launchFragment(destinationId: Int,
                      argBundle: Bundle? = null) {
                      val launchFragmentIntent = buildLaunchFragmentIntent(destinationId, argBundle)
                      activityRule.launchActivity(launchFragmentIntent)
                      }

                      private fun buildLaunchFragmentIntent(destinationId: Int, argBundle: Bundle?): Intent =
                      NavDeepLinkBuilder(InstrumentationRegistry.getInstrumentation().targetContext)
                      .setGraph(R.navigation.navigation)
                      .setComponentName(MainActivity::class.java)
                      .setDestination(destinationId)
                      .setArguments(argBundle)
                      .createTaskStackBuilder().intents[0]


                      destinationId being the fragment destination id in the navigation graph. Here is an example of a call that would be done once you are ready to launch the fragment:



                      launchFragment(R.id.target_fragment, targetBundle())

                      private fun targetBundle(): Bundle? {
                      val bundle = Bundle()
                      bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
                      return bundle
                      }


                      Doing it this way will launch the fragment directly. If your test works, then this proves that your app won't crash when the fragment is deep-linked to. It also ensures that the app will be stable if the process is killed by the system and it tries to rebuild the stack and relaunch the fragment.






                      share|improve this answer






























                        0














                        If you are using the Navigation Architecture component and you are using a single activity architecture in your app, you can quickly test each fragment by Deep linking to the target fragment (with appropriate arguments) at the beginning of the test.



                        For example:



                        @Rule
                        @JvmField
                        var activityRule = ActivityTestRule(MainActivity::class.java)

                        protected fun launchFragment(destinationId: Int,
                        argBundle: Bundle? = null) {
                        val launchFragmentIntent = buildLaunchFragmentIntent(destinationId, argBundle)
                        activityRule.launchActivity(launchFragmentIntent)
                        }

                        private fun buildLaunchFragmentIntent(destinationId: Int, argBundle: Bundle?): Intent =
                        NavDeepLinkBuilder(InstrumentationRegistry.getInstrumentation().targetContext)
                        .setGraph(R.navigation.navigation)
                        .setComponentName(MainActivity::class.java)
                        .setDestination(destinationId)
                        .setArguments(argBundle)
                        .createTaskStackBuilder().intents[0]


                        destinationId being the fragment destination id in the navigation graph. Here is an example of a call that would be done once you are ready to launch the fragment:



                        launchFragment(R.id.target_fragment, targetBundle())

                        private fun targetBundle(): Bundle? {
                        val bundle = Bundle()
                        bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
                        return bundle
                        }


                        Doing it this way will launch the fragment directly. If your test works, then this proves that your app won't crash when the fragment is deep-linked to. It also ensures that the app will be stable if the process is killed by the system and it tries to rebuild the stack and relaunch the fragment.






                        share|improve this answer




























                          0












                          0








                          0







                          If you are using the Navigation Architecture component and you are using a single activity architecture in your app, you can quickly test each fragment by Deep linking to the target fragment (with appropriate arguments) at the beginning of the test.



                          For example:



                          @Rule
                          @JvmField
                          var activityRule = ActivityTestRule(MainActivity::class.java)

                          protected fun launchFragment(destinationId: Int,
                          argBundle: Bundle? = null) {
                          val launchFragmentIntent = buildLaunchFragmentIntent(destinationId, argBundle)
                          activityRule.launchActivity(launchFragmentIntent)
                          }

                          private fun buildLaunchFragmentIntent(destinationId: Int, argBundle: Bundle?): Intent =
                          NavDeepLinkBuilder(InstrumentationRegistry.getInstrumentation().targetContext)
                          .setGraph(R.navigation.navigation)
                          .setComponentName(MainActivity::class.java)
                          .setDestination(destinationId)
                          .setArguments(argBundle)
                          .createTaskStackBuilder().intents[0]


                          destinationId being the fragment destination id in the navigation graph. Here is an example of a call that would be done once you are ready to launch the fragment:



                          launchFragment(R.id.target_fragment, targetBundle())

                          private fun targetBundle(): Bundle? {
                          val bundle = Bundle()
                          bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
                          return bundle
                          }


                          Doing it this way will launch the fragment directly. If your test works, then this proves that your app won't crash when the fragment is deep-linked to. It also ensures that the app will be stable if the process is killed by the system and it tries to rebuild the stack and relaunch the fragment.






                          share|improve this answer















                          If you are using the Navigation Architecture component and you are using a single activity architecture in your app, you can quickly test each fragment by Deep linking to the target fragment (with appropriate arguments) at the beginning of the test.



                          For example:



                          @Rule
                          @JvmField
                          var activityRule = ActivityTestRule(MainActivity::class.java)

                          protected fun launchFragment(destinationId: Int,
                          argBundle: Bundle? = null) {
                          val launchFragmentIntent = buildLaunchFragmentIntent(destinationId, argBundle)
                          activityRule.launchActivity(launchFragmentIntent)
                          }

                          private fun buildLaunchFragmentIntent(destinationId: Int, argBundle: Bundle?): Intent =
                          NavDeepLinkBuilder(InstrumentationRegistry.getInstrumentation().targetContext)
                          .setGraph(R.navigation.navigation)
                          .setComponentName(MainActivity::class.java)
                          .setDestination(destinationId)
                          .setArguments(argBundle)
                          .createTaskStackBuilder().intents[0]


                          destinationId being the fragment destination id in the navigation graph. Here is an example of a call that would be done once you are ready to launch the fragment:



                          launchFragment(R.id.target_fragment, targetBundle())

                          private fun targetBundle(): Bundle? {
                          val bundle = Bundle()
                          bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
                          return bundle
                          }


                          Doing it this way will launch the fragment directly. If your test works, then this proves that your app won't crash when the fragment is deep-linked to. It also ensures that the app will be stable if the process is killed by the system and it tries to rebuild the stack and relaunch the fragment.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 17 at 3:12

























                          answered Mar 17 at 1:45









                          Sean BlahoviciSean Blahovici

                          392412




                          392412






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33647135%2fandroid-independent-fragment-ui-testing-tool%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Xamarin.iOS Cant Deploy on Iphone

                              Glorious Revolution

                              Dulmage-Mendelsohn matrix decomposition in Python