有没有办法用多种测试方法运行Espresso测试,但只有一种设置方法?

peu*_*hse 9 android junit4 android-espresso

我今天做了一个简单的测试:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class WhenNavigatingToUsersView {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = 
        new ActivityTestRule(MainActivity.class);
    private MainActivity mainActivity;

    @Before
    public void setActivity() {
        mainActivity = mActivityRule.getActivity();
        onView(allOf(withId(R.id.icon), hasSibling(withText(R.string.users)))).perform(click());
    }

    @Test
    public void thenCorrectViewTitleShouldBeShown() {
        onView(withText("This is the Users Activity.")).check(matches(isDisplayed()));
    }

    @Test
    public void thenCorrectUserShouldBeShown() {
        onView(withText("Donald Duck (1331)")).check(matches(isDisplayed()));
    }
}
Run Code Online (Sandbox Code Playgroud)

但是对于每个setActivity运行的测试方法,如果你有10-15个方法,最后将是耗时的(如果你也有很多视图).

@BeforeClass似乎不起作用,因为它必须是静态的,因此也强迫它ActivityTestRule是静态的.

那么有没有其他方法可以做到这一点?而不是在同一个测试方法中有多个断言?

app*_*oll 4

@Before注释只能在包含初步设置的方法之前。初始化所需的对象,获取当前会话或当前活动,您就明白了。

它正在替换 ActivityInstrumentationTestCase2 中的旧setUp()方法,就像@After替换tearDown(). 这意味着它应该在类中的每个测试之前执行,并且应该保持这种状态。

在这个方法中你不应该有 no ViewInteraction、 no DataInteraction、 noAssertionsView动作,因为这不是它的目的。

在您的情况下,只需onView()setActivity()实际的测试方法中删除调用并将其放入实际的测试方法中,如果需要,可以放在每个测试方法中,如下所示:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class WhenNavigatingToUsersView {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = 
        new ActivityTestRule(MainActivity.class);
    private MainActivity mainActivity;

    @Before
    public void setActivity() {
        mainActivity = mActivityRule.getActivity();
        // other required initializations / definitions
    }

    @Test
    public void thenCorrectViewTitleShouldBeShown() {
        onView(allOf(withId(R.id.icon), hasSibling(withText(R.string.users)))).perform(click());
        onView(withText("This is the Users Activity.")).check(matches(isDisplayed()));
    }

    @Test
    public void thenCorrectUserShouldBeShown() {
        onView(allOf(withId(R.id.icon), hasSibling(withText(R.string.users)))).perform(click());
        onView(withText("Donald Duck (1331)")).check(matches(isDisplayed()));
    }
}
Run Code Online (Sandbox Code Playgroud)