简体   繁体   中英

Running Android ActivityUnitTestCase results in “RuntimeException: could not find test class”

Trying to generate a simple ActivityUnitTestCase to test various Fragments in my Android code.

public class MenuFragmentTest extends ActivityUnitTestCase<FragmentAdapter> {
    static {
        FragmentAdapter.setFragmentUnderTest(new MenuFragment());
    }

    public MenuFragmentTest() {
        super(FragmentAdapter.class);
    }

    public void testMenuOptions() {
        System.out.println(getActivity().findViewById(1));
    }
}

The generalized FragmentAdapter that I'm trying to use to test Fragments in the app:

public class FragmentAdapter extends FragmentActivity {
    static Fragment fragmentUnderTest;

    public static void setFragmentUnderTest(Fragment fragmentUnderTest) {
        FragmentAdapter.fragmentUnderTest = fragmentUnderTest;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout ll = new LinearLayout(this);
        ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        setContentView(ll);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(fragmentUnderTest, null);

        fragmentTransaction.commit();
    }
}

After the main app installs successfully, the Android JUnit Test Runner fails with

java.lang.RuntimeException: Could not find test class.  Class: com.XXX.core.MenuFragment

Why can the Test Runner not find the test class I am running?

Apparently the name of the test package really does matter:

From http://developer.android.com/tools/testing/testing_android.html :

If the application under test has a package name of com.mydomain.myapp, then the Android tools set the test package name to com.mydomain.myapp.test

Altering the package instrumentation targetPackage attribute is not good enough to allow you to create tests in the same package as the activity under test, even if the test is in the separate test project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM