I need to test a single activity in my Android app. The documentation of ActivityInstrumentationTestCase2
says:
This class provides functional testing of a single activity.
And the documentation of ActivityTestRule
says:
This rule provides functional testing of a single activity.
Almost the same words. Besides the two samples I've coded, do the same. So should I prefer ActivityTestRule
over ActivityInstrumentationTestCase2
or vice versa?
What I see is that extending ActivityInstrumentationTestCase2
looks like a JUnit3-styled test (its ancestor is junit.framework.TestCase
, and test methods should start with the word test
).
Using ActivityTestRule
package sample.com.sample_project_2;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {
@Rule
public ActivityTestRule<SecAct> mActivityRule = new ActivityTestRule(SecAct.class);
@Test
public void foo() {
onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE"));
}
}
Extending ActivityInstrumentationTestCase2
package sample.com.sample_project_2;
import android.test.ActivityInstrumentationTestCase2;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
public class ApplicationTest2 extends ActivityInstrumentationTestCase2<SecAct> {
public ApplicationTest2() {
super(SecAct.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
getActivity();
}
public void testFoo2() {
onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE 2"));
}
}
For your example, there is no difference. You can use any of them.
As per OO principle we shall "Prefer composition over inheritance". Usage of ActivityTestRule<>
is through composition while ActivityInstrumentationTestCase2<>
is though inheritance.
At times, I prefer to have a common base class for my test classes to reuse common initializations. This helps me to group tests according to a theme. ActivityTestRule<>
allows me to do such things.
For these reasons, I prefer ActivityTestRule<>
. Otherwise, I haven't seen any difference.