android / android-test

An extensive framework for testing Android apps
https://android.github.io/android-test
Apache License 2.0
1.15k stars 309 forks source link

Can't test fragment with an AppCompatActivity parent #394

Closed goldy1992 closed 4 years ago

goldy1992 commented 5 years ago

Description

I'm trying to write unit tests for a fragment which expects a parent activity of AppCompatActivity

Steps to Reproduce

public class MyFragment extends Fragment {
...
    @Override
    public void onViewCreated(@NonNull View view, Bundle bundle) {
     ...
            if (getActivity() instanceof AppCompatActivity) {
            AppCompatActivity activity = (AppCompatActivity) getActivity();

            activity.setSupportActionBar(titleBarFragment.getTitleToolbar());
            ActionBar actionBar = activity.getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
  ...
  }
}

When I try to test this this code will never be hit because I can't add a specific activity to the container. Meaning it can't be tested using Robolectric unit tests

Expected Results

An available method @NonNull public static <F extends Fragment> FragmentScenario<F> launch( @NonNull Class<F> fragmentClass, @Nullable Bundle fragmentArgs, @StyleRes int themeResId, @Nullable FragmentFactory factory, Activity activity) { will something along these lines be available in the future, or even better make the container use an Activity of type Activity instead of FragmentActivity

Actual Results

Have to write unit tests that cannot access the branch of the code

AndroidX Test and Android OS Versions

Android version 26 use of package androidx.fragment.app.testing; Robolectric 4.3

Link to a public git repo demonstrating the problem:

https://github.com/goldy1992/Mp3Player/blob/bugfix/issue-52/sonar-issues/app/src/main/java/com/example/mike/mp3player/client/views/fragments/MainFrameFragment.java

brettchabot commented 4 years ago

Looks like a dupe of https://issuetracker.google.com/121347222