JUnit android test classinheritance

I have simple Android application with some espresso tests. I want to write some base class so all of my test classes will inherit its @beforeClass and @afterClass methods, but the problem is when I do it like code example below, JUnit doesn't see any tests at al. I got Empty test suite. message. What's the problem?

Code example:

public class RealmTest {
    protected static Realm realm;

    @BeforeClass
    public static void beforeClass() {
        realm = Realm.getDefaultInstance();
        realm.setAutoRefresh(true);
    }

    @AfterClass
    public static void afterClass() {
        realm.close();
    }
}

@RunWith(AndroidJUnit4.class)
public class MainActivityTest extends RealmTest {
    @Rule
    public IntentsTestRule<MainActivity> activityTestRule = new IntentsTestRule<>(MainActivity.class);

    @Test
    public void startedFine() {
        assertNotNull(realm);
        onView(withId(R.id.button)).perform(click());
        intended(hasComponent(new ComponentName(getTargetContext(), EducationActivity.class)));
    }
}

If I'll run all tests, tests from MainActivityTest won't run. Thanks for your help, pls say if some additional info is needed.


Guessing: the JUnit environment is not looking for static methods. So maybe you simply drop that keyword from your base methods (guess you could keep your Realm static nonetheless; I assume you really only want one of those).

But then, another suggestion: don't use inheritance for test cases.

The point that makes test cases valuable to you is: they should quickly allow you to find and fix bugs in your production code.

But when your "setup" is hidden from your testcases - because things are not only happening in some @Before method ... but in a @Before method somewhere, in some different class ... well, that can seriously increase the time you will need to understand a failing testcase. Because: instead of just studying your test case, you find yourself digging around within test code in order to understand what exactly is happening besides the code in that failing test method itself!

Thus: be really careful to balancing "code duplication" versus "test case is easy to understand" aspects!

链接地址: http://www.djcxy.com/p/64106.html

上一篇: 编译程序并在终端中运行

下一篇: JUnit android测试classinheritance