gpt4 book ai didi

android - ActivityInstrumentationTestCase2 与 ActivityTestRule

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:55 26 4
gpt4 key购买 nike

我需要在我的 Android 应用程序中测试单个 Activity 。 ActivityInstrumentationTestCase2 的文档说:

This class provides functional testing of a single activity.

以及 ActivityTestRule 的文档说:

This rule provides functional testing of a single activity.

几乎相同的词。除了我编写的两个示例之外,执行相同的操作。所以我应该更喜欢 ActivityTestRuleActivityInstrumentationTestCase2反之亦然?

我看到的是扩展 ActivityInstrumentationTestCase2看起来像 JUnit3 风格的测试(它的祖先是 junit.framework.TestCase ,测试方法应该以单词 test 开头)。

使用 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"));

}
}

扩展 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"));

}
}

最佳答案

对于您的示例,没有区别。您可以使用其中任何一个。

根据 OO 原则,我们应该“优先组合而不是继承”。 ActivityTestRule<> 的用法是通过合成而ActivityInstrumentationTestCase2<>虽然是继承。

有时,我更喜欢为我的测试类提供一个公共(public)基类,以便重用公共(public)初始化。这有助于我根据主题对测试进行分组。 ActivityTestRule<>允许我做这样的事情。

出于这些原因,我更喜欢 ActivityTestRule<> .否则,我没有看到任何区别。

关于android - ActivityInstrumentationTestCase2 与 ActivityTestRule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37140559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com